简体   繁体   中英

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

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.

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})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM