Bluasul
Bluasul

Reputation: 325

Error adding new keys to a dictionary from list items

I'm going through Automate the Boring Stuff, this is the second project in chapter 5. For some reason my dictionary turns into "None" after calling the function that adds items to a dictionary. This is my code:

def displayInventory(anInventory):
    item_total = 0
    print("Inventory: \n")
    for i, j in anInventory.items():
        print(str(j) + " " + i)
        item_total += j
    print("\nTotal number of items: " + str(item_total))

def addToInventory(inventory, addedItems):
    for i in addedItems:
        if i in inventory:
            inventory[i] += 1
        else:
            inventory[i] = 1

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)

displayInventory(inv)

I've narrowed down the problem to the addToInventory function since the displayInventory function works fine on it's own. If I add a print statement right under the creation of the inv dictionary, it prints the dictionary. However, if I add the print statement right after the call to addToInventory function, it prints "None".

I was pretty confident the function worked well, so I would appreciate any help pointing out my mistake. Thanks!

Upvotes: 1

Views: 107

Answers (2)

qwerty_so
qwerty_so

Reputation: 36315

You do not return anything from addToInventory. So it's None.

Upvotes: 2

EsotericVoid
EsotericVoid

Reputation: 2576

Your addToInventory function doesn't return anything, so you're assigning the None value at this line:

inv = addToInventory(inv, dragonLoot)

Substitute the assignment with a simple method call:

addToInventory(inv, dragonLoot)

Upvotes: 2

Related Questions