首页 > 解决方案 > 删除元素后将所有嵌套字典元素重新排序为升序

问题描述

我知道这是这个的副本, 但是我看不到答案。提问者的问题可以通过列表来解决。但我不相信我的可以。我正在为我正在制作的业余游戏使用嵌套列表,有谁知道在我删除元素后如何将元素重新排序为升序。

potions = {
            1: {"name": "Potion of Bruh", "amount": 5},
            2: {"name": "Potion of Epic", "amount": 10},
            3: {"name": "Potion of Boi", "amount": 15},
            4: {"name": "Potion of Matt", "amount": 12},
            5: {"name": "Potion of Garfield", "amount": 3}
          }

for i in range(1, len(potions) + 1):
    if "Potion of Boi" == potions[i]["name"]:
        del potions[i]
print(potions)

标签: pythonlistdictionarydel

解决方案


您正在使用以整数为键的字典,而应该使用列表。您需要更改删除元素的方式,然后重新排序将正常工作:

potions = [
            {"name": "Potion of Bruh", "amount": 5},
            {"name": "Potion of Epic", "amount": 10},
            {"name": "Potion of Boi", "amount": 15},
            {"name": "Potion of Matt", "amount": 12},
            {"name": "Potion of Garfield", "amount": 3}
          ]
idx_to_remove = None
for idx, potion in enumerate(potions):
    if "Potion of Boi" == potion["name"]:
        idx_to_remove = idx
        break

if idx_to_remove is not None:
    potions.pop(idx_to_remove)

print(potions)

推荐阅读