Reputation: 21
I am a computer science student and for my GCSE course we need to complete a NEA course.
I chose the task where we make a dice game and I am stuck on a bit where I sort a dictionary into the top 5 scores.
My code reads a leaderboards.txt and converts it to a dictionary. Below is Leaderboard.txt
12 p2
13 p1
1412 p5
34 p3
213 p6
9 p4
And now I cant find anywhere which tells me how I can sort a dictionary by the top values. Below is my code
highscores={}
with open("Leaderboard.txt") as f:
for line in f:
(key,val) = line.split(" ")
highscores[int(key)] = val
How can I print top 5 values in the dict? Thanks
Upvotes: 1
Views: 287
Reputation: 15872
Here's a solution:
from collections import Counter
dct = {'p2':12,'p1':13,'p5':1412,'p3':34,'p6':213,'p4':9}
print(Counter(dct).most_common(5))
Output:
[('p5', 1412), ('p6', 213), ('p3', 34), ('p1', 13), ('p2', 12)]
Upvotes: 0
Reputation: 43320
In python 3.6, dictionaries are ordered by insertion order, so you need to extract all the keys and values, reorder them and then stick them in a new dictionary (limiting it to 5 entries whilst your at it)
original_dict = {
12: 'p2',
13: 'p1',
1412: 'p5',
34: 'p3',
213: 'p6',
9: 'p4'
}
sorted_items = sorted(original_dict.items(), key=lambda x: -x[0])
print({k: v for k, v in sorted_items[:5]})
{1412: 'p5', 213: 'p6', 34: 'p3', 13: 'p1', 12: 'p2'}
Upvotes: 2
Reputation: 3649
In order to sort the dictionary you would have to convert it to a type that can be sorted, such as a list. Alternatively, unless you have a particular need to use a dictionary, I would read the scores into a list to start with. That's a more suitable type for what you're attempting to do.
Upvotes: 0