1 #字典,键-值对,{}表示; 字典项不排序;可以用任意值做为键;
2 import operator
3 import pprint
4 myCat={'size':'fat','color':'gray','disposition':'loud'}
5 print(myCat['color'])#gray
6
7 myCat={3:'fat',10:'gray',5:'loud'}
8 print(myCat[3])#fat
9
10 print(myCat)
11 for v in myCat.values():#获取字典键列表
12 print(v)
13 for v in myCat.keys():#获取字典值列表
14 print(v)
15 for v in myCat.items():#获取字典项列表
16 print(v)#(3, 'fat') (10, 'gray') (5, 'loud')
17
18 for key,v in myCat.items():#获取字典项列表(多重赋值)
19 print('key:'+str(key)+' value:'+str(v))#key:3 value:fat key:10 value:gray key:5 value:loud
20
21 #检查字典中是否存在键或值 in, not in
22 print(3 in myCat.keys())#True
23 print(7 not in myCat.keys())#True
24 print(33 in myCat.keys())#False
25
26 #设置默认值setDefault()
27 myCat.setdefault(33,'maomao')#如果不存在33键,则设置33键及‘maomao’值;否则返回33对应值
28 print(myCat)#{3: 'fat', 10: 'gray', 5: 'loud', 33: 'maomao'}
29 print(myCat[10])#gray
30 print(myCat[3])#fat
31
32 print(myCat.setdefault(3,'maomao'))#直接返回的 fat ,因为有 3 键
33
34 print('Part2------------------------------')
35
36 #客人带东西
37 allGuests = {'Alice': {'apples': 5, 'pretzels': 12},
38 'Bob': {'ham sandwiches': 3, 'apples': 2},
39 'Carol': {'cups': 3, 'apple pies': 1}}
40
41 def totalBrought(guests, item):
42 numBrought = 0
43 for k, v in guests.items():
44 numBrought = numBrought + v.get(item, 0)
45 return numBrought
46
47 print('Number of things being brought:')
48 print(' - Apples ' + str(totalBrought(allGuests, 'apples')))
49 print(' - Cups ' + str(totalBrought(allGuests, 'cups')))
50 print(' - Cakes ' + str(totalBrought(allGuests, 'cakes')))
51 print(' - Ham Sandwiches ' + str(totalBrought(allGuests, 'ham sandwiches')))
52 print(' - Apple Pies ' + str(totalBrought(allGuests, 'apple pies')))