You are creating a fun video game. The data structure used to model the player's inventory is a dictionary. Where the key is a string describing the item in the inventory, and the value is an integer indicating how many of the item the player has. For example, a dictionary value of {'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means the player has 1 rope, 6 torches, 42 gold coins, etc. Write a function called displayInventory() that takes any possible inventory and displays it like this:
Inventory: 1 rope 42 gold coin 6 torch 1 dagger 12 arrow Total number of items: 62
The code is:
spam = {'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 = item_total + v print('Total number of items: ' + str(item_total)) displayInventory(spam)
5.6.2 List-to-dictionary functions for lists of fun game items
Suppose a government train's loot is represented as a list of strings like this:
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
Write a function called addToInventory(inventory, addedItems), where the inventory parameter is a dictionary representing the player's item list, and the addedItems parameter is a list, just like draonLoot.
The addToInventory() function should return a dictionary representing the updated inventory. Note that a list can contain multiple identical items.
code show as below:
def displayInventory(inventory): print ('Inventory:') item_total = 0 for k, v in inventory.items(): print(str(v) + ' ' + k) item_total = item_total + v print('Total number of items: ' + str(item_total))def addToInventory(inventory, addedItems): for item in dragonLoot: if item not in inventory.keys(): inventory.setdefault(item, 1) else: inventory[item] += 1 inv = {'gold coin': 42, 'rope': 1}dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']inv1 = addToInventory(inv,dragonLoot)print(inv)displayInventory(inv)
The result is shown below:
{'gold coin': 45, 'rope': 1, 'dagger': 1, 'ruby': 1} Inventory: 45 gold coin 1 rope 1 dagger 1 ruby Total number of items: 48