简体   繁体   English

如何获取字典中特定键最大的字典?

[英]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.

相关问题 将键添加到 dict 以获取 dict 的 dict - Adding key to dict to get a dict of dicts 如何计算字典列表中特定字典键的出现次数 - How to count occurrences of specific dict key in list of dicts 如何将字典/嵌套字典的字典转换为列表字典 - How do I convert dict of dicts/nested dicts into dict of list 如何在一个dicts列表中获得具有公共密钥最大值的整个dict - How to get whole dict with max value of a common key in a list of dicts 如何从 python 字典中找到特定键,然后从 Python 中的该键中获取值 - How can I find a specific key from a python dict and then get a value from that key in Python 如何计算字典列表中特定字典键的出现次数,一些字典值包含列表和 append 计数值 - How to count occurrences of a specific dict key in dicts list and some dicts values ​contains list and append the count in value 如何在字典或字典的字典中查找字符串是键还是值 - How to find whether a string either a key or a value in a dict or in a dict of dicts 如何在字典的字典中找到具有最高值的键? - how to find the key with the highest value in a dict of dicts? 如何找到用于匹配两个字典中的值的字典键? - How can I find dict keys for matching values in two dicts? 按键将字典分组后,获取字典列表中具有最大值的项目 - Getting the item with the maximum value in list of dicts after grouping the dict by key
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM