Home > Back-end >  Why is my dictionary being wiped after adding to it?
Why is my dictionary being wiped after adding to it?

Time:08-16

Currently working through the 'Automate the Boring Stuff' python tutorial and was completing an exercise at the end of the tutorial section.

I'm finding that when I add the information from a list into the main dictionary it works, but then after the function completes it seems to wipe the dictionary's contents.

inv = {'gold coin': 42, 'rope': 1}

def addToInventory(dict, addedItems):
    
    for i in addedItems:
        if i not in dict:
            dict[i] = 1
        else:
            dict[i] = dict[i]   1
        print(dict) #this exists so that I could check it wasn't a weird thing in the definition

def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(v, k)
        item_total  = v
    print("Total number of items: "   str(item_total))


dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)

displayInventory(inv) #the dictionary appears as empty

CodePudding user response:

addToInventory doesn't return anything, so inv = addToInventory(inv, dragonLoot) causes inv to be None. What you want instead is to just call addToInventory(inv, dragonLoot), which updates inv.

CodePudding user response:

A minor note for code refactoring purposes. I noticed that in your func addToInventory, there exists the following logic:

if i not in dict:
    dict[i] = 1
else:
    dict[i] = dict[i]   1

That could actually, be simplified just a little bit:

dict[i] = dict.get(i, 0)   1     

Or again a little further, using a defaultdict:

from collections import defaultdict


def addToInventory(dict, addedItems):
    for i in addedItems:
        dict[i]  = 1
        print(dict)  # this exists so that I could check it wasn't a weird thing in the definition


inv = defaultdict(int, **{'gold coin': 42, 'rope': 1})

But now on to the meat of the issue you were actually noticing / asking about. As indicated in the comments, that can be resolved in one of two ways. One approach could be to simply add a return statement at the end of the function body:

def addToInventory(dict, addedItems):
    for i in addedItems:
        if i not in dict:
            dict[i] = 1
        else:
            dict[i] = dict[i]   1
    # --> ADD this, here
    return dict

Or simply, without the return statement:

# return value is None, but let's say we still want to capture the `None` value
_ = addToInventory(inv, dragonLoot)
  • Related