I'm working on a problem given in chapter 5 of the book Automate Boring Stuff with Python in which I have to define a function (addToInventory
) which is supposed to add items in a list (named dragonLoot
) to a dictionary (called inv
) and another function (displayInventory
) which is supposed to display the new dictionary (inv
). The displayInventory
function works fine when I test it separately, but when I run the complete program I'm getting RuntimeError: dictionary size changed during iteration
. Here is my code:
def displayInventory(inv):
for k,j in inv.items(): #to display inv in format of a game inventory
print(k,end=':')
print(j)
def addToInventory(inv,dragonLoot):
for a,b in inv.items(): #a represents key and b represents values
for c in range(len(dragonLoot)-1):
if a==dragonLoot[c]: #to check items in dragonLoot
b+=1 #adding 1 to value if its corresponding key exists in dragonloot
else:
inv.setdefault(dragonLoot[c],1) #adding the new item if it dosent exist in dragonLoot
return inv
inv = {'gold coin':42,'rope':1}
dragonLoot = ['gold coin','dagger','gold coin','gold coin','ruby']
inv = addToInventory(inv,dragonLoot)
displayInventory(inv)
here is the error:
Traceback (most recent call last):
File "c:\users\murali\mu_code\addtoinventory.py", line 16, in <module>
inv = addToInventory(inv,dragonLoot)
File "c:\users\murali\mu_code\addtoinventory.py", line 7, in addToInventory
for a,b in inv.items():
RuntimeError: dictionary changed size during iteration
please tell me where I'm making a mistake and also what kind of mistakes can cause such error.I have also found different solution to this problem but i want to know problem in this program.