-1

I've been looking with no success for a way to sum the total number of items in a list. Using ATBS beginner python book. My code is as follows:

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

print('Inventory:')

for item, inven_count in items.items():
    item_total = ???
    print(str(inven_count) + ' ' + item)

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

The item_total line is what I'm unsure of. I know that the answer I want is 62, but I've been unable to think of the right way to word my code to reach that answer. Thanks very much!

biscuit
  • 29
  • 2

2 Answers2

2

Use this method if you wish to keep the loop for displaying the items as well. Here, you can use a variable to keep track of the total and item_total += inven_count is shorthand for item_total = item_total + inven_count

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

print('Inventory:')

item_total = 0

for item, inven_count in items.items():
    item_total += inven_count
    print(str(inven_count) + ' ' + item)

print('Total number of items: ' + str(item_total))
Parth Shah
  • 1,237
  • 10
  • 24
2

You don't care about the keys in the dictionary, just the values so you can use items.values(). You want the sum so use the built in function sum().

Putting that all together gives:

item_total = sum(items.values())

No for loop required!

IronFarm
  • 407
  • 4
  • 5