Python开发文本游戏删除嵌套字典键触发KeyError报错如何解决
KeyError报错原因
- 你的
rooms是存储所有房间数据的顶层字典,它的键是各个房间的名称(比如Kitchen、Main Hall),不存在以道具名(比如你报错里的Chef Gem)为键的条目。你执行del rooms[current_room['search']]时,current_room['search']取到的值是道具名,用这个值去索引rooms字典自然会触发键不存在的错误。 - 你操作的目标对象完全错了:你需要删除的是当前所在房间
current_room这个子字典里的item键,而不是rooms顶层字典的键。
正确实现逻辑
有两种常用方案可选:
方案1:直接删除current_room的item键
拾取道具后直接删除当前房间字典里的item字段即可,修改后的代码如下:
if 'item' in current_room: picked_item = current_room['item'] print('Found the {}, shiny. I will put it in my inventory I guess.'.format(picked_item)) player_inventory.append(picked_item) print("{}'s inventory :".format(player_name), player_inventory) # 直接删除当前房间的item键 del current_room['item'] continue else: print('There is nothing of interest here, maybe I should search another room.') continue
方案2:用布尔值标记道具是否被拾取
如果你想用提到的布尔值方案,不需要删除键,只要新增布尔字段标记拾取状态即可,首先修改房间结构:
'name': 'Kitchen', 'north': 'Main Hall', 'south': 'Food Storage', 'item': { 'name': 'Chef Gem', 'picked': False }
对应的逻辑代码修改为:
if 'item' in current_room and not current_room['item']['picked']: picked_item = current_room['item']['name'] print('Found the {}, shiny. I will put it in my inventory I guess.'.format(picked_item)) player_inventory.append(picked_item) print("{}'s inventory :".format(player_name), player_inventory) # 修改布尔值标记为已拾取 current_room['item']['picked'] = True continue else: print('There is nothing of interest here, maybe I should search another room.') continue
内容的提问来源于stack exchange,提问作者Jonathan Pun
相关产品推荐
相关产品推荐

