cguer
cguer

Reputation: 3

Comparing value of same key between multiple dictionaries

I am trying to create a function that will take an arbitrary number of dictionaries as arguments and return the dictionary with the lowest value for the 'qty' key. All dictionaries have the same number of items and are formatted as follows:

dictA = {'qty':1000, 'color':'red'}
dictB = {'qty':3000, 'color':'red'}
dictC = {'qty':5000, 'color':'red'}
...

I know how to return the min value :

def minQty(*args):
    return min([i['qty'] for i in args])

But I am having trouble grasping how to return the dictionary itself in that situation.

The desired output would look like this:

>>> minQty(dictA, dictB, dictC)
dictA

Upvotes: 0

Views: 423

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1121972

Use the key argument to the min() function; it lets you pick one of the dictionaries based on the return value of the key (called per dictionary):

def minQty(*args):
    return min(args, key=lambda d: d['qty'])

Instead of a lambda, you can also use the operator.itemgetter() function to create a callable for the key:

from operator import itemgetter

def minQty(*args):
    return min(args, key=itemgetter('qty'))

Demo:

>>> from operator import itemgetter
>>> dictA = {'qty':1000, 'color':'red'}
>>> dictB = {'qty':3000, 'color':'red'}
>>> dictC = {'qty':5000, 'color':'red'}
>>> def minQty(*args):
...     return min(args, key=itemgetter('qty'))
... 
>>> minQty(dictA, dictB, dictC)
{'color': 'red', 'qty': 1000}

Upvotes: 3

Padraic Cunningham
Padraic Cunningham

Reputation: 180411

You can use operator.itemgetter as the key to min to find the dict with the lowest value for qty:

dictA = {'qty':1000, 'color':'red'}
dictB = {'qty':3000, 'color':'red'}
dictC = {'qty':5000, 'color':'red'}

from operator import itemgetter

def minQty(*args):
    return min(args,key=itemgetter("qty"))

print(minQty(dictA, dictB, dictC))

If you potentially have dicts that may not have the key then you should use dict.get with a default value of float(inf):

def minQty(*args):
    return min(args, key=lambda x:x.get('qty',float("inf")))

Upvotes: 3

Related Questions