我有一本字典,看起来像这样:
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}