所以,我正在为我的游戏制作一个清单系统,但是像往常一样,有一个错误。这当然是我的错,但我想不出办法来。我需要的代码添加到dict项不替换当前键。例如,一个玩家钓到一条鱼:
inventory = {} #This is the dict to hold all the items
for x in range(1,10):
inventory['slot{0}'.format(x)] = {'type':'Fish'}
break
但是如果你钓到两条鱼,它总是占据第一个位置
###Output:
{'slot1':{'type':'Fish'}}
所以我试着做了一个if,一个关于插槽是否已满的声明,然后再试下一个
for x in range(1,10):
if inventory['slot{0}'.format(x)] != {}:
x += 1
inventory['slot{0}'.format(x)] = {'type':'Fish'}
break
以下是捕获的两条鱼的预期产量:
###Output
{'slot1':{'type':'fish'},'slot2':{'type':'fish}}
但是我得到一个关键错误,嵌套字典不存在。所以,我需要一些帮助。你知道吗
下面是预期输出的代码。实际上,您正在尝试在分配dict键之前访问它。你知道吗
正如在评论中提到的,这确实是一个列表的工作。包括完整的字典版本。你知道吗
带列表:
使用dict:
如果值为“无”,则表示为空:
或者,如果不希望出现任何键,则表示为空:
对于上述任何一项:
您也可以完全删除
slotname
,如果没有按下键的原因,只使用整数作为键。你知道吗您可以将新数据输入到新的dict
temp = {}
,然后将其与主dictinventory = {**inventory, **temp}
合并相关问题 更多 >
编程相关推荐