【问题标题】:How do i remove a key from a dictionary based on value? [duplicate]如何根据值从字典中删除键? [复制]
【发布时间】:2021-08-04 11:09:55
【问题描述】:
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)将被删除。

有什么建议吗?我感谢任何和所有建议,甚至是负面的建议

【问题讨论】:

  • 这里的字典结构错误,最好使用一个可以排序的元组列表并替换最后一个条目
  • 或者更好的是,将列表设为heap。然后就像将新值推送到堆上一样简单,然后调用pop 删除最低值。

标签: python


【解决方案1】:

你可以试试这样的:

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}

【讨论】:

  • 哟!!!生病了
  • 哈哈,如果这回答了你的问题,请投票并接受答案(根据 StackOverflow 规则)。
【解决方案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}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多