python - Why does this function change my dictionary to None? -
i'm writing practice program add items list existing dictionary
def addtoinventory(inventory, addeditems): in addeditems: inventory[i] = inventory.get(i,0) + 1 stuff = {'gold coin': 42, 'rope': 1} loot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby'] stuff = addtoinventory(stuff, loot)
why stuff changed none after running this?
in fact code have 1 mistake. dictionary in python mutable when modify in fonction modifying 1 pass argument. because function not return when write:
stuff = addtoinventory(stuff, loot)
you assign stuff none.
you have 2 choice: return dictionary @ end of function:
def addtoinventory(inventory, addeditems): in addeditems: inventory[i] = inventory.get(i,0) + 1 return inventory
or not reassign stuff:
addtoinventory(stuff, loot)
Comments
Post a Comment