有没有办法在带有 python 的 if 语句中将项目添加到字典中?
Is there a way of adding an item to a dictionary within an if statement with python?
我正在制作一个基于文本的冒险游戏,并且我正在尝试根据玩家在其库存中有一个密钥来将一个项目添加到一个目录中。
我已经尝试了我能找到的所有解决方案,其中 none 行得通。我想这可能是因为我的语法与其他词典不同。
if 'key' in inventory:
print('Well done for killing all monsters on the first floor! You can
now
travel upstairs from the hall')
'Hall' ['upstairs'] = 'Landing'
'Hall' : {
'south' : 'Kitchen',
'east' : 'Dining Room',
'north' : 'Library',
'west' : 'Game Room',
},
请告诉我另一种放置方式
'Hall' ['upstairs'] = 'Landing'
无需更改所有目录,因为我还有许多其他房间。
您提到了您的 "different syntax",我对此并不熟悉 - 所以我想这实际上是您出现问题的地方。请参阅下面我的改编 - 这是您期望的行为吗?
Hall = {
'south': 'Kitchen',
'east': 'Dining Room',
'north': 'Library',
'west': 'Game Room',
}
inventory = ['key']
if 'key' in inventory:
print('Well done for killing all monsters on the first floor! You can now travel upstairs from the hall')
Hall['upstairs'] = 'Landing'
print(Hall)
# Output: {'south': 'Kitchen', 'east': 'Dining Room', 'north': 'Library', 'west': 'Game Room', 'upstairs': 'Landing'}
注意:您需要先定义字典 Hall
,然后才能像这样分配键值对 Hall['upstairs'] = 'Landing'
。
我正在制作一个基于文本的冒险游戏,并且我正在尝试根据玩家在其库存中有一个密钥来将一个项目添加到一个目录中。
我已经尝试了我能找到的所有解决方案,其中 none 行得通。我想这可能是因为我的语法与其他词典不同。
if 'key' in inventory:
print('Well done for killing all monsters on the first floor! You can
now
travel upstairs from the hall')
'Hall' ['upstairs'] = 'Landing'
'Hall' : {
'south' : 'Kitchen',
'east' : 'Dining Room',
'north' : 'Library',
'west' : 'Game Room',
},
请告诉我另一种放置方式
'Hall' ['upstairs'] = 'Landing'
无需更改所有目录,因为我还有许多其他房间。
您提到了您的 "different syntax",我对此并不熟悉 - 所以我想这实际上是您出现问题的地方。请参阅下面我的改编 - 这是您期望的行为吗?
Hall = {
'south': 'Kitchen',
'east': 'Dining Room',
'north': 'Library',
'west': 'Game Room',
}
inventory = ['key']
if 'key' in inventory:
print('Well done for killing all monsters on the first floor! You can now travel upstairs from the hall')
Hall['upstairs'] = 'Landing'
print(Hall)
# Output: {'south': 'Kitchen', 'east': 'Dining Room', 'north': 'Library', 'west': 'Game Room', 'upstairs': 'Landing'}
注意:您需要先定义字典 Hall
,然后才能像这样分配键值对 Hall['upstairs'] = 'Landing'
。