如何根据值从字典中删除键?

2024-06-28 19:57:54 发布

您现在位置:Python中文网/ 问答频道 /正文

highscore = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10}

为了提供上下文,我正在制作一个有记分板的游戏。游戏结束后,如果玩家的分数高于字典中的最高值,则会删除最低值。本词典中的键是示例玩家名称

例如,如果一个新玩家(我们称之为“L”)得了11分,“a”(分数为1)将被删除

有什么建议吗?我感谢所有的建议,即使是负面的建议


Tags: 名称游戏示例字典玩家分数建议最低值
2条回答

您可以尝试以下方法:

d = {'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

search = 1
{x: y for x, y in d.items() if y != search}
# Out[22]: {'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

您可以尝试以下方法:

highscore = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5, 'f':6, 'g':7, 'h':8, 'i':9, 'j':10}
score = 11
values = list(highscore.values())

# if the player's score is higher than the highest value in the dictionary
# then reconstruct the dictionary with the minimum value removed
if all(score > value for value in values):
    highscore = {k:v for k, v in highscore.items() if v!=min(values)}

print(highscore)

输出:

{'b': 2, 'c': 3, 'd': 4, 'e': 5, 'f': 6, 'g': 7, 'h': 8, 'i': 9, 'j': 10}

相关问题 更多 >