python-3.x - 从字典列表中获取最大值的键
问题描述
我有一个这样的字典列表:
ex = [{'Michigan': 0.8},{'New York': 0.2}]
我想提取"Michigan"
,因为 0.8 是最大的。
我尝试了以下,但并不简单,最后一部分不起作用,因为*item.values()
不被接受(SyntaxError
)。
scores = []
for item in ex:
scores.append(*item.values())
max_score = max(scores)
for item in ex:
if (*item.values()) == max_score:
print(item.keys())
输入:
ex = [{'Michigan': 0.8},{'New York': 0.2}]
预期输出:
'Michigan'
补充:我也尝试使用 itemgetter 按值对列表进行排序,但它不起作用:
print(sorted(ex, key = lambda item: item.keys())
解决方案
In [15]: list(max(ex, key=lambda x: list(x.values())).keys())[0]
Out[15]: 'Michigan'
推荐阅读
- javascript - 如何使用 jest 和“react-dom/test-utils”对反应过滤器组件进行单元测试?
- database - Django如何将文件分配给现有模型,而不上传它
- google-apps-script - 在该函数中引用包含用户定义函数的单元格
- c# - 运行 power shell 命令以在 c# 上按进程获取 GPU 使用情况
- java - Flink 客户端在打印堆栈跟踪时阻塞
- java - 如何在二叉搜索树数组实现中找到最大值的索引?
- reactjs - 如何在反应中以antd形式添加自定义验证?
- printing - Electron-pos-printer 应用程序打印时有奇怪的结果静默:true 设置但未设置时打印正常
- c# - ASP.NET Core MVC:添加 OAuth 缺少 Startup.CS OWIN
- java - 是否可以将项目连接到不同的 BD,就像您将其连接到不同的 API 一样?