删除元素后将所有嵌套字典元素重新排序为升序

Re-Ordering all nested dictionary elements back to ascending numerical order after deleting an element

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

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)

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

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)

使用排序函数

potions = {
        9: {"name": "Potion of Bruh", "amount": 5},
        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}
      }

potions.popitem()
sorted_d = dict(sorted(potions.items(),reverse=False))
print('Dictionary in ascending order by value : ',sorted_d)