python - 删除元素后将所有嵌套字典元素重新排序为升序
问题描述
我知道这是这个的副本, 但是我看不到答案。提问者的问题可以通过列表来解决。但我不相信我的可以。我正在为我正在制作的业余游戏使用嵌套列表,有谁知道在我删除元素后如何将元素重新排序为升序。
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)
推荐阅读
- html - div内内容的排序
- linux - Linux 记录器的替代品
- oracle-cloud-infrastructure - 无法列出公共存储桶中的内容
- python - 在 NumPy 中向量化 2D 卷积
- docker - 与不同桥接网络中的多个 docker-compose.yml 通信
- markdown - 如何按顺序自动编号 MkDocs 图形
- java - Java固定线程池竞争条件?
- python-3.x - 如何使用 if 语句同时读取列表中的所有元素?
- python - 按 2 列分组并在 Pandas 中为每个组合打印数据
- ios - Apple 开发者注册错误:此时无法完成您在 Apple 开发者计划中的注册