0

I am trying to create a high score system for my game, but only want to display the top 5 high scores. I used a dictionary to store the scores and the names of the players. I want the program to remove the first score once there are more than 5 items. How do I remove items from a dictionary based on their order?

I tried to use .pop(index) like so:

highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
if len(highscores) > 5:
    highscores.pop(0)

However I get an error:

Traceback (most recent call last):
  File "c:\Users\-----\Documents\Python projects\Python NEA coursework\test.py", line 3, in <module>
    highscores.pop(0)
KeyError: 0

Anyone know why this happens?

I found a solution:

highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
thislist = []
for keys in highscores.items():
    thislist += keys
highscores.pop(thislist[0])
Nomzz
  • 23
  • 5
  • Dictionaries don't have an "order" per se. Recent Python versions remember the insertion order, but they're still not data structures where you work with an item at some specific *offset*. Use a different data structure, like a list, or deque. – deceze Dec 21 '21 at 14:42
  • In this thread you'll find your answer: [How can I remove a key from a Python dictionary?](https://stackoverflow.com/questions/11277432/how-can-i-remove-a-key-from-a-python-dictionary) – PetoMPP Dec 21 '21 at 14:43

2 Answers2

1

What you can do is turn your dict into a list of tuples (the items), truncate that, then turn back into a dict. For example, to always keep only the last 5 values inserted:

highscores = dict(list(highscores.items())[-5:])

(Note that it is idempotent if there were fewer than 5 items to start with).

Pierre D
  • 24,012
  • 7
  • 60
  • 96
  • Worth noting that the question asker almost certainly actually wants to remove the smallest _value_ (or at least, they will, once they realize that removing the first index is only correct when the dictionary items are already in sorted order, as they happen to be in the example given). To do that, it's a little more complex because you need to sort on the values first: `highscores.pop(sorted(highscores.items(), key=lambda kv: kv[1])[0][0])`. This is not idempotent, however. – AdamKG Dec 21 '21 at 14:48
  • Thank you so much. I think this solution works best as I don't need to have the if statement either. – Nomzz Dec 21 '21 at 16:17
  • 1
    @AdamKG In my actual program I have stored the dictionary in a file and will only add to it if the score is higher than the highest score. I don't exactly want to make a leader board, just a documentation of the highest scores players got. – Nomzz Dec 21 '21 at 16:19
1

dict is not in ordered way. So first create ordered dict with the order you want.

You can try:

>>> import collections
>>> highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
>>> highscores = collections.OrderedDict(highscores)
>>> highscores.pop(list(new_dict.keys())[0])
'54'
>>> highscores
OrderedDict([('player2', '56'), ('player3', '63'), ('player4', '72'), ('player5', '81'), ('player6', '94')])
Harsha Biyani
  • 7,049
  • 9
  • 37
  • 61