首页 > 解决方案 > 从字典列表中获取最大值的键

问题描述

我有一个这样的字典列表:

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())

标签: python-3.xdictionary

解决方案


In [15]: list(max(ex, key=lambda x: list(x.values())).keys())[0]                                                                                                                
Out[15]: 'Michigan'

推荐阅读