Python 如何解决这个问题?RuntimeError:字典在迭代期间更改了大小
当我在函数中使用Python 如何解决这个问题?RuntimeError:字典在迭代期间更改了大小,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,当我在函数中使用向字典添加一个项时,它给出了以下错误: inv = { "rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12 } dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] def AddInventory(invloop, lst): for item in lst: for k,v in invloop.it
向字典添加一个项时,它给出了以下错误:
inv = { "rope": 1, "torch": 6, "gold coin": 42, "dagger": 1, "arrow": 12 }
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def AddInventory(invloop, lst):
for item in lst:
for k,v in invloop.items():
if item == k:
v += 1
else:
invloop[item] = 1
return(invloop)
inv = AddInventory(inv, dragonLoot)
事实上,您不应该在循环时将项目添加到库存中。更重要的是,您不需要内部循环,因为字典的优点是您可以通过键直接访问:您可以使用in
操作符测试它是否有键
因此,请改为:
def AddInventory(invloop, lst):
for item in lst:
if item in invloop:
invloop[item] += 1
else:
invloop[item] = 1
return(invloop)