def addToInventory(inventory, addedItems):
dicts = {}
for i in addedItems:
dicts[i] = addedItems.count(i)
for k, v in inventory.items():
if k in dicts:
dicts[k] = dicts[k] + inventory[k]
else:
dicts[k] = inventory[k]
return dicts
def displayInventory(invertory):
print('Invertory:')
for k, v in invertory.items():
print(v, k)
inv = {'gold coin': 42, 'rope': 1}
dragonLoot = ['gold coin', 'dagger', 'gold coin', 'gold coin', 'ruby']
invs = addToInventory(inv, dragonLoot)
displayInventory(invs)
输出如下
Invertory:
45 gold coin
1 dagger
1 ruby
1 rope
def displayInventory(invertory):
print('Invertory:')
totalNumber = 0
for k, v in invertory.items():
print(v, k)
totalNumber += v
print('Total number of items :{0}'.format(totalNumber))