Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the key with the maximum nested key in a python dictionary

I have a dictionary like so:

my_dictionary = {
      'key1': {'a': 1, 'b': 1, 'c': 10}, 
      'key2': {'a': 1, 'b': 1, 'c': 11}, 
      'key3': {'a': 1, 'b': 1, 'c': 12}
}

How can I compare the 'c' subkeys of this dictionary, find the greatest one, and return the corresponding parent key of that dictionary (in this case I want to output 'key3' as it's 'c' key is highest). Thanks!

like image 760
YPCrumble Avatar asked Dec 20 '22 17:12

YPCrumble


1 Answers

max optionally accepts a callable argument for modifying the comparison:

>>> d
{'key1': {'a': 1, 'b': 1, 'c': 10},
 'key2': {'a': 1, 'b': 1, 'c': 11},
 'key3': {'a': 1, 'b': 1, 'c': 12}}
>>> max(d, key=lambda v: d[v]['c'])
'key3'
like image 99
wim Avatar answered Jan 05 '23 00:01

wim