python实践项目三:将列表添加到字典

1、创建一个字典,其中键是字符串,描述一个物品,值是一个整型值,说明有多少该物品。例如,字典值{'rope': 1, 'torch': 6, 'gold coin': 42, 'dagger': 1, 'arrow': 12}意味着有 1 条绳索、 6 个火把、 42 枚金币等。

2、写一个名为 displayInventory()的函数,显出出字典中所有物品及数量

3、写一个名为 addToInventory(inventory, addedItems)的函数, 其中 inventory 参数是一个字典, 存储物品清单, addedItems 参数是一个列表,存储需要更新的清盘。addToInventory()函数应该返回一个字典,表示更新过后的物品清单。

 1 #!/usr/bin/python
 2 # -*- coding: UTF-8 -*-
 3 #打印字典
 4 def displayInventory(inventory):
 5     print 'Inventory:'
 6     item_total=0
 7     for k,v in inventory.items():
 8         print str(v)+' '+k
 9         item_total+=v
10     print 'Total number of items:'+str(item_total)
11 #列表添加到字典
12 def addToInventory(inventory,addItems):
13     for k in addItems:
14         if k in inventory.keys():
15             inventory[k]+=1
16         else:
17             inventory[k]=1
18     return  inventory
19 
20 #初始字典
21 inv={'gold coin':42,'rope':1}
22 #需要添加的列表
23 dragonLoot=['gold coin','dagger','gold coin','gold coin','ruby']
24 #将列表添加到字典
25 inv=addToInventory(inv,dragonLoot)
26 #显示更新后的字典
27 displayInventory(inv)

显示结果:

猜你喜欢

转载自www.cnblogs.com/heyangblog/p/10995483.html