Home > Back-end >  How to get the max value from a dictionary inside of a dictionary?
How to get the max value from a dictionary inside of a dictionary?

Time:02-27

I have a dictionary that looks like this

a_dictionary = {"a": {"green_count: 12"}, "b": {"green_count: 13"}, "c": {"green_count: 2"}}

How can I find the highest green_count value and return the key 'b'?

I know how to do this for a value directly inside a dictionary key max_key = max(a_dictionary, key=a_dictionary.get however I don't know how to do this for a value that is inside a dictionary in a dictionary.

CodePudding user response:

Assuming you really have a nested dictionary (and thus that you syntax is incorrect):

a_dictionary = {"a": {"green_count": 12}, "b": {"green_count": 13}, "c": {"green_count": 2}}

max(a_dictionary, key=lambda x: a_dictionary[x].get('green_count',0))

Output: 'b'

  • Related