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

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -