Home > front end >  Why is the dictionary returning None when using the function, while it returns what I want inside th
Why is the dictionary returning None when using the function, while it returns what I want inside th

Time:04-22

I'm learning Python and I'm trying to write some program to manage "inventory". I have come with a way to change list to dictionary, it adds up the values but returns None in the end. The code looks like this:

def addToInventory(inventory, addedItems):
    backpack = {}
    for i in addedItems:
        backpack.setdefault(i, 0)
        backpack[i]  = 1
        print(backpack)
    for k, v in backpack.items():
        if k not in inventory.keys():
            inventory.setdefault(k, v)
        elif k in inventory.keys():
            inventory[k]  = backpack[k]
    print(inventory)


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

The print(inventory) returns what I want, but print(inv) returns None. Can you help me understand what I do wrong? Sorry if this is trivial. Thank you in advance.

CodePudding user response:

def addToInventory(inventory, addedItems):
    backpack = {}
    for i in addedItems:
        backpack.setdefault(i, 0)
        backpack[i]  = 1
        print(backpack)
    for k, v in backpack.items():
        if k not in inventory.keys():
            inventory.setdefault(k, v)
        elif k in inventory.keys():
            inventory[k]  = backpack[k]
    print(inventory)
    return inventory # This was missing!!


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