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.
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'
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With