[英]How can I access values from a key that stores more than one value in a dictionary in python?
My dictionary looks like this: 我的字典看起来像这样:
{James: [10, 7, 9], 'Bob': [3, 8, 4], 'Charles': [6, 2, 5]}
What I want to do is, output each user's score in order of who got the highest score. 我想做的是,按照获得最高得分的顺序输出每个用户的得分。 And with their name.
并加上他们的名字。 At the moment, I am only able to print the student with the highest score:
目前,我只能打印得分最高的学生:
inverse = [(value, key) for key, value in score_dict.items()]
print (max(inverse)[1])
The output is: 输出为:
James
The output that I am trying to get is: 我想要得到的输出是:
James 10
Bob 8
Charles 6
You don't need your inverse dictionary at all; 您根本不需要逆字典。 you're not trying to find the single highest score among all of the students;
你不试图找到在所有学生的单项最高分; instead, you want to find the highest score for each student.
相反,您想找到每个学生的最高分数。
To do so, do the following: 为此,请执行以下操作:
scores = {'James': [10, 7, 9], 'Bob': [3, 8, 4], 'Charles': [6, 2, 5]}
for name in scores.keys:
print(name + " " + str(max(scores[name])))
This avoids the need for a new dictionary. 这避免了需要新的字典。 The most complex part of this is
str(max(scores[name]))
, which, reading from innermost to outermost: "Take name, find name's list of scores, find the max value in their scores, and then turn that into a string". 最复杂的部分是
str(max(scores[name]))
,从最里面到最外面读:“取名字,找到名字的分数列表,找到分数的最大值,然后将其变成串”。
You can simply create a list of tuples with userwise highscore and later sort it with score. 您可以简单地创建具有用户明智的高分的元组列表,然后再使用得分对其进行排序。 Something like this,
像这样
x = {'James': [10, 7, 9], 'Bob': [3, 8, 4], 'Charles': [6, 2, 5]}
y = [(k, max(v)) for k, v in x.items()]
for k, v in sorted(y, key=lambda a: a[1], reverse=True):
print (k, v)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.