python - 查找字典列表中的最大值并返回键
问题描述
我有我有这样的数据结构:
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
我怎样才能做到这一点?
解决方案
您无需遍历字典列表 -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
推荐阅读
- python-3.x - tensorflow 和 keras 中的新功能,用于使用神经网络进行图像处理和检测
- opencv - 如何为一个视频的所有帧获得相同大小的拼接图像?
- javascript - GSAP [Timeline/ScrollTrigger/fromTo] 起始值在第一次动画化之前不被接受
- sql-server - 如何使用 SSIS 将多个不同的结构化 CSV 文件加载到一个表中?
- algorithm - 您如何加载不断更新的分页数据?
- python - 如何按特定字符在键中出现的次数对字典键进行排序?
- javascript - 尝试使用专有协议发布和获取 xml
- android - 如何在 gradle 中为 Android Asset Pack(不是 Android apk 模块)设置自定义资产位置?
- c++ - 通过模板参数传递数据,C++
- spring-boot - 用过mybatisPlus。bean 实例化失败;嵌套异常是 org.springframework.beans.BeanInstantiationException