I am aware that this is copy of this however, there was no answer that I could see. The asker's problem could be fixed by lists. But I do not believe that mine can. I am using nested lists for an amateur game I'm making, does anyone know how re-order the element back to ascending numerical order after I delete 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)
You are using a dictionary keyed by integers and should be using a list instead. You'll need to change how you remove elements but then the reordering will work properly:
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)