繁体   English   中英

在键值对中找到最大值-Python字典

[英]Finding the highest value in a key-value pair - python dictionaries

我有一本字典,看起来像这样:

marks = {'Alex': [9, 8], 'John': [10, 10], 'Raj': [10, 9, 5]}

我希望能够为每个人选择最高分,并通过以下方式将其存储在新词典中:

highest_score = {'Alex': [9], 'John': [10], 'Raj': [10]} 

我猜:

highest_score = {}   
for key, values in marks.items(): 
    #Find highest value
    #store highest value in highest_score

如何找到最高值并将其存储在新词典中?

提前致谢。

highest_score = {key: max(values) for key, values in marks.iteritems()}

请注意,这将为您提供以下结果:

highest_score = {'Alex': 9, 'John': 10, 'Raj': 10} 

如果您实际上希望每个结果仍在列表中,请改用[max(values)]

highest_score = {k: [max(v)] for k, v in marks.iteritems()}
In [50]: highest = {k: [(max(v))] for k,v in marks.iteritems()}

In [51]: highest
Out[51]: {'Alex': [9], 'John': [10], 'Raj': [10]}

在列表上使用max函数。

marks = {'Alex': [9, 8], 'John': [10, 10], 'Raj': [10, 9, 5]} 
highest_score = {}   
    for key, values in marks.items():
        highest_score[key] = max(values)
print highest_score                      

输出:

{'Alex': 9, 'John': 10, 'Raj': 10}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM