Thomas Wagenaar
Thomas Wagenaar

Reputation: 6749

Grabbing key of dictionary in dictionary with highest value

So I have got the following dictionary (Python 3):

mydict = {'a' : {'c' : 1}, 'b' : {'c' : 2}}

As you see a and b are similar dictionaries, they have the same keys, however the values of these keys are not always the same.

What I want of this dictionary: the key ('a' or 'b') which value (=dictionary) contains the key with the highest value compared to the other dictionaries.

I have been looking at the max function but no luck so far.

Upvotes: 4

Views: 597

Answers (2)

Anand S Kumar
Anand S Kumar

Reputation: 90869

max() function supports key argument to which you can pass a function object (like lambda) and this function would receive each value of the list/iterable you passed to max, and should return the value on which to calculate the max.

Example -

>>> mydict = {'a' : {'c' : 1}, 'b' : {'c' : 2}}
>>> max(mydict, key=lambda x: mydict[x]['c'])
'b'

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1121276

To get the key for the nested dictionary with the highest value for the specific key ('c') use:

max(mydict, key=lambda k: mydict[k]['c'])

or use

max(mydict, key=lambda k: mydict[k].get('c', float('-inf')))

if not all nested dictionaries have the 'c' key. The float('-inf') return value ensures that those keys are not picked as the maximum.

The key function is called for each key from mydict, and its return value is used to select which one is the maximum:

>>> mydict = {'a' : {'c' : 1}, 'b' : {'c' : 2}}
>>> max(mydict, key=lambda k: mydict[k]['c'])
'b'

Upvotes: 5

Related Questions