访问嵌套字典中的值



我正在为我的第一个脚本项目用python编写一个基于文本的游戏,不知道如何访问嵌套字典中的最后一个值。我正在尝试访问键"物品"的值,以便当玩家进入一个房间时,它会显示该房间中的物品。然后根据玩家的输入,道具将被添加到库存中。我正在努力,所以我很感激你的帮助。

rooms = {'Living Room': {'South': 'Study', 'North': 'Kitchen', 'East': 'Bedroom', 'West': 'Bathroom'},
'Bedroom': {'North': 'Dining Room', 'West': 'Living Room', 'South': 'Sunroom', 'item': 'Glasses'},
'Dining Room': {'West': 'Kitchen', 'South': 'Bedroom', 'item': 'Napkin'},
'Kitchen': {'South': 'Living Room', 'East': 'Dining Room', 'West': 'Basement', 'item': 'Cheese'},
'Basement': {'East': 'Kitchen', 'South': 'Bathroom', 'item': 'Catnip'},
'Bathroom': {'East': 'Living Room', 'North': 'Basement', 'South': 'Walk-in Closet', 'item': 'Water'},
'Walk-in Closet': {'North': 'Bathroom', 'East': 'Study', 'item': 'Shoes'},
'Study': {'North': 'Living Room', 'East': 'Sunroom', 'West': 'Walk-in Closet', 'item': 'Cotton Balls'},
'Sunroom': {'North': 'Bedroom', 'West': 'Study', 'item': 'Cat'}
}

评论中的解决方案组合如下:

roomName = 'Bedroom' # Select the room the user is currently entering.
roomItem =  rooms[roomName].get('item', 'Nothing') # 'Nothing' when no item in the room

这样,您可以为每个房间选择一个项目,如果没有项目,则返回'Nothing'。您也可以返回None或任何其他值作为默认值。

最新更新