Python嵌套字典替换子键:如何保留原物品键与对应属性?
问题解决:背包槽位替换物品时保留物品键名
我用Tkinter开发文字RPG时,设置了嵌套字典inventory(背包)和items(物品库),通过items['物品名']访问物品。
原有结构
背包inventory
inventory = { 'slot1': { 'Empty': { 'name': "empty", 'icon': "images/icons/emptyslot.png", 'equippable': False, 'color': "black" }, }, 'slot2': { 'Empty': { 'name': "empty", 'icon': "images/icons/emptyslot.png", 'equippable': False, 'color': "black" }, } }
物品库items
items = { # ONE HANDED WEAPONS 'Dirk': { 'name': 'Dirk', 'mindamage': 1, 'maxdamage': 5, 'blockvalue': 0, 'agility': 2, 'strength': 0, 'intelligence': 0, 'coins': 20, 'color': "gray", 'icon': "images/icons/dirk.png", 'equippable': True, 'gearslot': "both" }, 'Empty': { 'name': "empty", 'icon': "images/icons/emptyslot.png", 'equippable': False, 'color': "black" }, }
问题描述
执行inventory['slot1'] = items['Dirk']替换空物品后,slot1丢失了'Dirk'子键,变成了纯物品属性字典:
- 赋值前slot1:
{'Empty': {'name': 'empty', ...}} - 赋值后slot1:
{'name': 'Dirk', ...}
解决方案
问题根源是直接用物品属性字典覆盖了槽位的嵌套字典结构,正确做法是保持槽位为包含物品键名的嵌套字典,有两种实现方式:
方式一:直接赋值新的嵌套字典
inventory['slot1'] = {'Dirk': items['Dirk']}
方式二:清空槽位后添加键值对
如果需要保留槽位原有字典对象(比如绑定了其他引用),可以先清空再添加:
# 清空slot1原有内容 inventory['slot1'].clear() # 添加Dirk的键值对 inventory['slot1']['Dirk'] = items['Dirk']
两种方式执行后,slot1的结构都会变为:
{'Dirk': {'name': 'Dirk', 'mindamage': 1, ...}}
完全匹配初始的嵌套结构要求。
内容的提问来源于stack exchange,提问作者Robin Wright
相关产品推荐
相关产品推荐

