[英]Is there a way of adding an item to a dictionary within an if statement with python?
I am making a text-based adventure game, and am trying to add an item to a directory on the basis that the player has a key in their inventory. 我正在制作一个基于文本的冒险游戏,并试图根据玩家的库存中有钥匙,将一个物品添加到目录中。
I have tried every solution I could find, and none of them worked. 我尝试了所有可以找到的解决方案,但没有一个起作用。 I think this is maybe because I have a different syntax to the other dictionaries.
我认为这可能是因为我的语法与其他字典不同。
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',
},
Please tell me another way to put 请告诉我另一种放置方式
'Hall' ['upstairs'] = 'Landing'
without changing all of the directory, as I have numerous other rooms. 无需更改所有目录,因为我还有许多其他房间。
You mentioned your "different syntax", which I am not familar with - so I guess this is actually where your problems arise. 您提到了您不熟悉的“不同语法”-所以我想这实际上就是您出现问题的地方。 See my Adaptations bellow - is this the behavior you expected?
请参阅下面的“我的改编”-这是您期望的行为吗?
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'}
Note: You need to define your dictionary Hall
before you can assign key-value-pairs like this Hall['upstairs'] = 'Landing'
. 注意:您需要先定义字典
Hall
然后才能分配键值对,例如this Hall['upstairs'] = 'Landing'
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.