Quick Start Python programming practice project title, welcome to testify and optimization!
You create a fun video game. For data structure modeling on the players list item is a word
Code. Wherein the key is a string that describes the list of the items, the value is an integer value, indicating how much the player object
product. For example, dictionary values { 'rope': 1, ' torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12} means that the play
house has a rope, torch 6, 42 gold coins and so on.
Write a function named displayInventory (), which accepts any list of possible items and is shown below:
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))
displayInventory(stuff)
operation result:
Inventory:
1 rope
6 torch
42 gold coin
1 dagger
12 arrow
Total number of items: 62
Function list to the dictionary, a list of games for the fun items
assumed train spoils conquer such a list of strings represented:
dragonLoot = [ 'Gold COIN', 'Dagger', 'Gold COIN', 'Gold COIN', 'Ruby' ]
write a function addToInventory (inventory, addedItems) named parameters in which the inventory
is a dictionary representing the player's list of items (the same as the previous item), addedItems argument is a list,
just like dragonLoot.
addToInventory () function should return a dictionary representing the updated list of items. Notice that the column
table can contain multiple identical items. Your code might look like this:
def addToInventory(inventory, addedItems):
# your code goes here
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
inv = addToInventory(inv, dragonLoot)
displayInventory(inv)
New Code:
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))
#displayInventory(stuff)
def addToInventory(inventory, addedItems):
# your code goes here
for i in addedItems:
if i in inventory.keys():
inventory[i] += 1
else:
inventory.setdefault(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)
operation result:
Inventory:
45 gold coin
1 rope
1 dagger
1 ruby
Total number of items: 48