'Trouble with output for Fantasy Game Inventory

I'm a beginner working on the Automate the boring stuff with Python book. I'm stuck on this practice problem. The instructions are as follows:

List to Dictionary Function for Fantasy Game Inventory:

Imagine that a vanquished dragon’s loot is represented as a list of strings like this:

dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

Write a function named addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player’s inventory (like in the previous project) and the addedItems parameter is a list like dragonLoot. The addToInventory() function should return a dictionary that represents the updated inventory. Note that the addedItems list can contain multiples of the same item. Your code could look something like this:

def addToInventory(inventory, addedItems):


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

The previous program (with your displayInventory() function from the previous project) would output the following:

Inventory:
45 gold coin
1 rope
1 ruby
1 dagger
Total number of items: 48

My code is as follows

    def addtoinventory(inventory,lootlist):
    for i in range(len(lootlist)):
        if lootlist[i] in inventory:
            inventory[lootlist[i]] = inventory[lootlist[i]] + 1

    else:
        inventory.setdefault(lootlist[i],1)

        return inventory


def displayinventory(inventory):
    total_items = 0

    for k,v in inventory.items():
        print(k + ' : ' + str(v))

        total_items = total_items + v

    print("Total number of items: " + str(total_items))


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

My output is like this:

gold coin : 45
ruby : 1
rope : 1
Total number of items: 47

What am I doing wrong?



Solution 1:[1]

I think your indent of else: is wrong. You should use if-else, but your code is for-else. The code below works well.

def addtoinventory(inventory,lootlist):
    for i in range(len(lootlist)):
        if lootlist[i] in inventory:
            inventory[lootlist[i]] = inventory[lootlist[i]] + 1
        else:
            inventory.setdefault(lootlist[i],1)
    return inventory

The result is below.

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

Solution 2:[2]

I copied your code and it worked just fine for me, apart from the items and their numbers being in the wrong order, which is easily fixed if you change the print line to this:

print(str(v)+' : '+k)

Solution 3:[3]

This is how I solved it. I wasn't able to get rid of the brackets though, and for some reason the pprint didn't work. But this code serves the purpose anyway...

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

#Turn dragonLoot list in to a dictionary:
list={}
for i in dragonLoot:
    if i not in list:
        list.setdefault(i, 1)
    elif i in list:
        list[i] = list[i] +1

#Merge dictionaries:
for i, v in list.items():
    if i not in inv:
        inv.setdefault(i, 1)
    elif i in inv:
            inv[i]=inv[i]+v

import pprint

print('Inventory: ')
pprint.pprint(inv, width=1)
print('')
total=0

#Count the total number of items:
for i, v in inv.items():
    total=total+v

print('Total number of items: ' + str(total))

Solution 4:[4]

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

def addToInventory(inventory, addItems):
    for k in range(len(addItems)):
        inventory.setdefault(addItems[k], 0)
        inventory[addItems[k]] += 1
    return(inventory)

inventory = {'rope': 1, 'torches': 6, 'gold coins': 42, 'daggers': 28, 'arrows': 12, 'knives': 50}
dragonLoot = ['gold coins', 'daggers', 'gold coins', 'gold coins', 'ruby']
updatedInventory = addToInventory(inventory, dragonLoot)
displayInventory(updatedInventory)
print("Inventory updated.")

Solution 5:[5]

Try the following:

def addToInventory(dragonLoot,inv):
    count={}
    for item in dragonLoot:
        count.setdefault(item,0)
        count[item]=count[item]+1

    for k in count.keys():
        if k in inv.keys():
            inv[k]=inv[k]+count[k]
    print(inv)

Solution 6:[6]

You're searching for range in Dictionary and your code has issues with unexpected indent

    playerInventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
    dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']

    def addToInventory(inventory, addedItems):
        for i in addedItems:
            if i not in inventory:
                inventory.setdefault (str(i), 1)
            else:
                inventory[i] = inventory[i] + 1
        return inventory

    playerInventory = addToInventory(playerInventory, dragonLoot)
    print(playerInventory)

Solution 7:[7]

i just got into the book and here how I solved it, seems pretty simple:

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


def addToInventory(backpack, added_items):
    for i in added_items:
        if i in backpack:
            backpack[i] += 1
        else:
            count = 0
            count += 1
            backpack[i] = count

    return backpack

Solution 8:[8]

inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
def addToInventory(inventory, addedItems):
        for i in range(len(addedItems)):
            if addedItems[i] in inventory:
                inventory[addedItems[i]] = inventory[addedItems[i]] + 1
            else:
                inventory.setdefault(addedItems[i],1)
        return inventory                
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)

Solution 9:[9]

Here's my solution:

# inventory.py
# stuff = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}
def displayInventory(inventory):
    print("Inventory:")
    item_total = 0
    for k, v in inventory.items():
        print(str(v) + ' ' + k)
        item_total += v
    
    print("Total number of items: " + str(item_total))

def addToInventory(inventory, addedItems):
    for i in addedItems:
        #copy() is for to avoid RuntimeError: dictionary changed size during iteration
        for k, v in inventory.copy().items():  
            if k == i:
                inventory[k] = v + 1
            if i not in inventory.keys():
                inventory[i] = 1
                    
    return inventory
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
# displayInventory(stuff)

Solution 10:[10]

This is how I figured it out. wanted to share since is the first one I did without help. hope it helps and all feedback is welcome.

`

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

def addToInventory(inventory, addedItems):
    for loot in addedItems:
        inventory.setdefault(loot, 0)
        for k, v in inventory.items():
            if loot == k:
                inventory[loot] = v + 1

def displayInventory(inventory):
    totalItems = 0
    for k, v in inventory.items():
        print(str(v) + '---' + str(k))
        totalItems += v
    print('Total number of items: '+ str(totalItems))
  
addToInventory(inv, dragonLoot)  
displayInventory(inv)

`

Solution 11:[11]

This is how i did it. I think this is a clean solution for the addToInventory() function. What do you think? Or did i missed something?

PlayerInventory = {"gold coin": 42, "rope": 1}
dragonLoot = ["gold coin", "dagger", "gold coin", "gold coin", "ruby"]


def displayInventory(inventory):  # Displays the Inventory
    print("Inventory:")
    cnt = 0
    for k, v in inventory.items():
        print(k + " : " + str(v))
        cnt += v
    print(f"Total number of items: {cnt}")


def addToInventory(inventory, addedItems):  # Add items to the provided inventory
    for item in addedItems:  # Loops trough the provided list.
        inventory.setdefault(item, 0)  # Checks if the key exists. If not, adds it with a value of 0.
        inventory[item] += 1  # Adds 1 to the value.
    return inventory  # returns the complete Dictionary


PlayerInventory = addToInventory(PlayerInventory, dragonLoot)
displayInventory(PlayerInventory)

Solution 12:[12]

def add(inventory,items):
    for j in items:

        for i ,k in inventory.copy().items():
            if i==j:
                inventory[i]=k+1
            else:
                inventory.setdefault(j,1)                   
    print(inventory)            

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

I think this will be the best approach

Solution 13:[13]

from collections import Counter
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
dl = (dict(Counter(dragonLoot)))


    def addToInventory(inventory, addedItems):
            for key, v in addedItems.items():
                    if key not in inventory:
                            inventory.setdefault(key, 1)
                    elif key in inventory:
                            inventory[key] = inventory[key] + v
            return inventory
    addToInventory(inv,dl)
    print(inv)

Solution 14:[14]

items={'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}

def displayInventory(*inventory):
    total_items = 0
    for i, j in items.items():
        print(j, i)
        total_items += j
    print("Total number of items: " + str(total_items))

displayInventory()