Warm tip: This article is reproduced from serverfault.com, please click

How can I get the dict whose specific key is maximum in a dict of dicts?

发布于 2020-12-04 05:27:24

Say I have a dictionary with max and min temperatures of every month:

t = {
    'jan': {
        'max': 21,
        'min': 12
    },
    'feb': {
        'max': 18,
        'min': 15
    },
    'mar': {
        'max': 20,
        'min': 17
    }
}

Now I want to know which month has the biggest max value. For this example, I would like to get this dict as a result (since 21 > 18 in Feb, and 21 > 20 in Mar):

'jan': {
    'max': 21,
    'min': 12
}

I can get what is the biggest dictionary easily with max():

>>> max(t.values(), key=lambda s: s.get('max'))
{'max': 21, 'min': 12}

However, it is important to me to get the dict's key as well, so instead of just {'max': 21, 'min': 12} I want the full 'jan': {'max':21, 'min':12}.

The current approach I use is a basic loop checking for the values:

max_dict = dict()
max_key = ''
for k, v in t.items(): 
    if max_dict.get('max',0) <= v.get('max', 0): 
        max_dict = v 
        max_key = k 

And now max_key contains "jan", while max_dict contains {'max': 21, 'min': 12}.

However, I guess some kind of sorting with max can provide the result in a more straight-forward way.

Questioner
fedorqui 'SO stop harming'
Viewed
0
jakevdp 2020-12-04 13:31:39

You could do the max of t.items() with an appropriate key:

>>> max(t.items(), key=lambda s: s[1]['max'])
('jan', {'max': 21, 'min': 12})