allGuests={'Alice':{'apples':5,'pretzels':12},
'Bob':{'ham sandwiches':3,'apples':2},
'Carol':{'cups':3,'apple pies':1}}
def totalBrought(guests,item):#定义函数中两个变量
numBrought=0
for k,v in guests.items():# 遍历字典列表
numBrought=numBrought+v.get(item,0)#返回指定键(item)的值
return numBrought
print('Number of things being brought:')
print(' - Apples '+str(totalBrought(allGuests,'apples')))
print(' - cups '+str(totalBrought(allGuests,'cups')))
print(' - Cakes '+str(totalBrought(allGuests,'cakes')))
print(' - Ham Sandwiches '+str(totalBrought(allGuests,'ham sandwiches')))
print(' - apple Pies '+str(totalBrought(allGuests,'apple pies')))
dict.items()
把字典中每对 key 和 value 组成一个元组,并把这些元组放在列表中返回
dict = {'one': 1, 'two': 2, 'three': 3}
for a,b in dict.items()#两个参数分别对应元祖中两个元素
print(key + ':' + str(value))
one:1
two:2
three:3for i in d.items():#当参数只有一个时
print(i)
('one', 1)
('two', 2)
('three', 3)
dict.get(key, default=None)
寻找dict中指定key的value
展开过程
num=0
K=Alice,V={'apples':5,'pretzels':12}
num=0+{'apples':5,'pretzels':12}.get(apples,0)
num=0+5
num=5
K=Bob,V={'ham sandwiches':3,'apples':2}
num=5+{'ham sandwiches':3,'apples':2}.get(apples,0)
num=5+2
num=7
K=Carol,V={'cups':3,'apple pies':1}
num=7+{'cups':3,'apple pies':1}.get(apples,0)
num=7+0
num=7
return num
num=7