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:
JavaScript
x
4
1
highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
2
if len(highscores) > 5:
3
highscores.pop(0)
4
However I get an error:
JavaScript
1
5
1
Traceback (most recent call last):
2
File "c:Users-----DocumentsPython projectsPython NEA courseworktest.py", line 3, in <module>
3
highscores.pop(0)
4
KeyError: 0
5
Anyone know why this happens?
I found a solution:
JavaScript
1
6
1
highscores = {"player1":"54", "player2":"56", "player3":"63", "player4":"72", "player5":"81", "player6":"94"}
2
thislist = []
3
for keys in highscores.items():
4
thislist += keys
5
highscores.pop(thislist[0])
6
Advertisement
Answer
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:
JavaScript
1
2
1
highscores = dict(list(highscores.items())[-5:])
2
(Note that it is idempotent if there were fewer than 5 items to start with).