-1

I'm writing a practice program to add items from a list to a existing dictionary

def addToInventory(inventory, addedItems):
    for i 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 is stuff changed to None after running this?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
tripleMalt
  • 253
  • 2
  • 7

2 Answers2

3

In fact your code is almost good you have just one mistake. Dictionary in python are mutable then when you modify it in your fonction your modifying the one you pass as argument. But because your function do not return anything when you write:

stuff = addToInventory(stuff, loot)

you assign stuff to None.

you have two choice: return the dictionary at the end of the function:

def addToInventory(inventory, addedItems):
    for i in addedItems:
        inventory[i] = inventory.get(i,0) + 1
    return inventory

or do not reassign stuff:

 addToInventory(stuff, loot)
RomainL.
  • 997
  • 1
  • 10
  • 24
2

There's no return statement in your function so it returns nothing - None.

Solution? Add return statement in your function

def addToInventory(inventory, addedItems):
    for i in addedItems:
         inventory[i] = inventory.get(i,0) + 1
    return inventory
maestromusica
  • 706
  • 8
  • 23