Reputation: 289495
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.
Upvotes: 2
Views: 37
Reputation: 86310
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})
Upvotes: 2