Nomzz
Nomzz

Reputation: 23

How do you remove an item from a dictionary by its index value?

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])

Upvotes: 0

Views: 699

Answers (3)

Delvin Anthony
Delvin Anthony

Reputation: 11

counter = 0
for i in highscores:
    if counter == (indx):
        tasks.pop(i)
        break
    counter += 1

Not sure if this would help anyone but it worked for me. It works by having a counter start at the index 0 and then counting up for each iteration of the for loop until the counter reaches the desired index in which that index gets removed and you can break out of the for loop.

Upvotes: 0

Harsha Biyani
Harsha Biyani

Reputation: 7268

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')])

Upvotes: 1

Pierre D
Pierre D

Reputation: 26271

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).

Upvotes: 1

Related Questions