1

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

Chris Doyle
  • 10,703
  • 2
  • 23
  • 42
ICookixz
  • 21
  • 3

3 Answers3

2

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'}
Sayse
  • 42,633
  • 14
  • 77
  • 146
  • good answer, i would just add that for the users data they read data from a file so they will have string data so they will need to wrap `x[0]` as `int(x[0])` to be sure to sort score numerically. – Chris Doyle Nov 15 '19 at 10:27
  • @ChrisDoyle - Thats true although the op already does that in their question – Sayse Nov 15 '19 at 10:29
  • Thanks it works, do you know how I can print it so that when it is printed, It is in a better format? – ICookixz Nov 15 '19 at 10:30
  • @ICookixz - You need to iterate over the items in your output dictionary and then format them however you like – Sayse Nov 15 '19 at 10:31
  • 1
    @Sayse ah ok it seems someone has edited the OP question changing int() to str() for some reason on the dict key. I have updated the OP question to use int() again as it orignally did. – Chris Doyle Nov 15 '19 at 11:30
  • How can I do that? @Sayse – ICookixz Nov 15 '19 at 12:00
0

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)]
Sayandip Dutta
  • 15,602
  • 4
  • 23
  • 52
0

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.

Kemp
  • 3,467
  • 1
  • 18
  • 27