Satarupa Guha
Satarupa Guha

Reputation: 1307

How to find the key corresponding to the maximum value in a dictionary of dictionary using max() function?

I know how to find the key corresponding to the maximum value in a dictionary, thanks to the answers to the following quesyions on Stackoverflow -

Print the key of the max value in a dictionary the pythonic way,

key corresponding to maximum value in python dictionary,

Getting key with maximum value in dictionary?, etc.

But I am not being able to understand how these will work out for a dictionary of dictionary.

Example-
I have a dictionary of dictionary d[x][l]. Suppose, I need to find the following- For a particular l='green', I need to find the corresponding value of x for which d[x]['green'] is maximum.

How to use the max() function in this case? I want to avoid looping over. I was hoping to find something equivalent to the MATLAB way of doing it in a matrix- max(d(:,l)).

d[x][l] takes integer values, and so does x.

Upvotes: 1

Views: 991

Answers (2)

Sahil Panhalkar
Sahil Panhalkar

Reputation: 29

d = {10: 100, 81:500}
s=max(d,key=d.get)
print(s)

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121336

Use a lambda:

max(d, key=lambda x: d[x]['green'])

The key function is called with each key in d; if you want to find the key for which d[key]['green'] is highest, you return exactly that.

Demo:

>>> d = {10: {'green': 42}, 81: {'green': 5, 'blue': 100}}
>>> max(d, key=lambda x: d[x]['green'])
10

d[10]['green'] is the highest value, so 10 is returned.

Upvotes: 3

Related Questions