0

I am trying to write a simple program that takes a dictionary (inventory) of {item: integer}, and then sums the integer values of all the keys.

Currently, this is what I have, and it isn't working:

inventory = {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 125, 'bow': 1}

def displayInventory(inventory):
    print('Welcome to your pack. Currently you have:\n')
    total_items = 0
    for k,v in inventory.items():
        total_items = total_items + v.get(v, 0)
    return total_items
    print(total_items)

This is the error which I get:

Traceback (most recent call last): File "C:\Users\Kyle\Documents\displayInventory.py", line 16, in displayInventory(inventory) File "C:\Users\Kyle\Documents\displayInventory.py", line 7, in displayInventory total_items = total_items + v.get(v, 0) AttributeError: 'int' object has no attribute 'get'

I am looking for someone to walk me through what I am missing, not simply give the right code to make this happen, as I can't learn this if I don't understand what is going on.

Any insight/guidance is greatly appreciated.

Thanks in advance.

1 Answers1

1

In your for loop, you are already destructuring each pair "k, v" stands for key and value. Hence, you're getting that error because you're trying to get your value, from the value.

Just change the body of your for loop to total_items += v and you should get what you're looking for.

Jacob
  • 1,697
  • 8
  • 17