首页 > 解决方案 > 查找字典列表中的最大值并返回键

问题描述

我有我有这样的数据结构:

   dataset = [{'country': 'Afghanistan',
     'continent': 'Asia',
     '1990': 500,
     '1991': 500,
     '1992': 500,
     '1993': 1000},
    {'country': 'Albania',
    'continent': 'Europe',
    '1990': 100,
    '1991': 100,
    '1992': 100,
    '1993': 100}
    {'country': 'Algeria',
    'continent': 'Africa',
    '1990': 500,
    '1991': 500,
    '1992': 1000,
    '1993': 1000
    }]

我需要找到 1991 年的最大值并创建一个带有键的字典 - 国家,这个最大值在哪里,我们正在寻找的年份(1991 年)和找到的最大值。

我本来想这样弄的,但没有成功。

    new_dict = {}
    str_year = str(year)
    for dict_ in dataset:
        for key, values in dict_.items():
        max_val = max(dict_, key=lambda x:x[str_year])
        new_dict = {'country' : dict_['country'], 'year': year, 'cases': max_val}
     return new_dict

我怎样才能做到这一点?

标签: pythondictionary

解决方案


您无需遍历字典列表 -max()将为您提供您想要使用的字典。然后您只需要提取正确的字段,如下所示:

max_val = max(dataset, key=lambda x:x[str_year])
new_dict = {'country' : max_val['country'], 'year': year, 'cases': max_val[str_year]}

(另请注意,您的定义dataset在语法上不正确)

{'country': 'Albania',
    'continent': 'Europe',
    '1990': 100,
    '1991': 100,
    '1992': 100,
    '1993': 100},
               ^^   missing the close of the dictionary

推荐阅读