Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is the dictionary returning None when using the function, while it returns what I want inside that function in Python

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading