从字典列表中获取最大值的键

时间:2020-07-20 19:28:58

标签: python-3.x dictionary

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

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

1 个答案:

答案 0 :(得分:1)

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