Ivan Lendl
Ivan Lendl

Reputation: 125

How to get the max value from a dictionary inside of a dictionary?

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.

Upvotes: 1

Views: 605

Answers (2)

edd313
edd313

Reputation: 1449

You could try with a NestedDict. Install ndicts first

pip install ndicts

Then

from ndicts.ndicts import NestedDict

a_dictionary = {"a": {"green_count": 12}, "b": {"green_count": 13}, "c": {"green_count": 2}}
nd = NestedDict(a_dictionary)

maximum = max(nd.values())

This works with nested dictionaries of any depth.

Upvotes: 1

mozway
mozway

Reputation: 260335

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'

Upvotes: 1

Related Questions