python - How to fix this? RuntimeError: dictionary changed size during iteration -
when added item dictionary in a
function, it's giving error:
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): item in lst: k,v in invloop.items(): if item == k: v += 1 else: invloop[item] = 1 return(invloop) inv = addinventory(inv, dragonloot)
indeed should not add items inventory while looping on it. what's more, don't need inner loop, because advantage of dictionary have direct access via keys: can test whether has key or not in
operator.
so instead:
def addinventory(invloop, lst): item in lst: if item in invloop: invloop[item] += 1 else: invloop[item] = 1 return(invloop)
Comments
Post a Comment