简体   繁体   English

如何通过索引值从字典中删除项目?

[英]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.我正在尝试为我的游戏创建一个高分系统,但只想显示前 5 个高分。 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.一旦超过 5 个项目,我希望程序删除第一个分数。 How do I remove items from a dictionary based on their order?如何根据顺序从字典中删除项目?

I tried to use .pop(index) like so:我尝试像这样使用.pop(index)

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

What you can do is turn your dict into a list of tuples (the items), truncate that, then turn back into a dict.您可以做的是将您的 dict 变成一个元组(项目)列表,截断它,然后再变成一个 dict。 For example, to always keep only the last 5 values inserted:例如,要始终只保留最后插入的 5 个值:

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

(Note that it is idempotent if there were fewer than 5 items to start with). (请注意,如果开始的项目少于 5 个,则它是幂等的)。

dict is not in ordered way. dict不是有序的。 So first create ordered dict with the order you want.所以首先用你想要的顺序创建ordered dict

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM