Reputation: 29
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
Upvotes: 0
Views: 68
Reputation: 3581
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".
Upvotes: 1
Reputation: 3626
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)
Upvotes: 0