Fantasy game inventory — Ch. 5 Automate the Boring Stuff Here is a practice exercise — Fantasy Game Inventory \$-\$


  You are creating a fantasy video game. The data structure to model the
  player’s inventory will be a dictionary where the keys are string
  values describing the item in the inventory and the value is an
  integer value detailing how many of that item the player has. For
  example, the dictionary value {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches,
  42 gold coins, and so on.
  
  Write a function named display_inventory() that would take any
  possible “inventory” and display it like the following -
  
  Inventory:
12 arrows
42 gold coins
1 rope
6 torches
1 dagger
Total number of items: 62

  
  Hint - You can use a for loop to loop through all the keys in a
  dictionary.


I have written the following code. Any feedback is highly appreciated.

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

def display_inventory(inventory):
    total_items = 0
    print ("Inventory:")
    for item in inventory:
        print(str(inventory[item]) + ' ' + item)
        total_items += inventory[item]
    print("Total number of items: " + str(total_items))

if __name__ == '__main__':
    display_inventory(stuff)
I am suggesting to use fstrings and the dictionary items() method.

The

print(f'{value} {key}')


instead of

print(str(inventory[item]) + ' ' + item)


is more neatly:

def display_inventory(inventory):
    total_items = 0 
    print ("Inventory:")

    for key, value in inventory.items():
        print(f'{value} {key}')
        total_items += value

    print(f'Total number of items: {total_items}')


Also, you can just calculate the total number in the needed place by the sum() function and the dictionary values() method. Then, you are not needing the total_items variable.

def display_inventory(inventory):
    print ("Inventory:")

    for key, value in inventory.items():
        print(f'{value} {key}')

    print(f'Total number of items: {sum(inventory.values())}')