[英]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.现在我想知道哪个月的
max
。 For this example, I would like to get this dict as a result (since 21 > 18 in Feb, and 21 > 20 in Mar):对于这个例子,我想得到这个 dict 结果(因为 21 > 18 在二月和 21 > 20 在三月):
'jan': {
'max': 21,
'min': 12
}
I can get what is the biggest dictionary easily with max()
:我可以使用
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}
.但是,获取字典的密钥对我来说也很重要,所以我想要完整
'jan': {'max':21, 'min':12}
而不是{'max': 21, 'min': 12}
'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}
.现在
max_key
包含“jan”,而max_dict
包含{'max': 21, 'min': 12}
。
However, I guess some kind of sorting with max can provide the result in a more straight-forward way.但是,我猜想用 max 进行某种排序可以以更直接的方式提供结果。
You could do the max of t.items()
with an appropriate key:您可以使用适当的键执行
t.items()
的最大值:
>>> max(t.items(), key=lambda s: s[1]['max'])
('jan', {'max': 21, 'min': 12})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.