Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 613
Thomas Wagenaar Avatar asked Jan 07 '23 17:01

Thomas Wagenaar


2 Answers

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'
like image 194
Martijn Pieters Avatar answered Jan 30 '23 11:01

Martijn Pieters


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'
like image 37
Anand S Kumar Avatar answered Jan 30 '23 09:01

Anand S Kumar