字典
书上的allguess={'1':{'apples':5,'pretzeles':12},
'2':{'ham sandwiches':3,'apples':2},
'3':{'cups':3,'apple pies':1}}
def a(guests,item):
numbrount=0
for k,v in guests.items():
numbrount=numbrount+v.get(item,0)
return numbrount
print('number of things being brought:')
print('apples '+str(a(allguess, 'apples')))
print('cups '+str(a(allguess, 'cups')))
print('cakes '+str(a(allguess, 'cakes')))
print('ham sandwich '+str(a(allguess, 'ham sandwiches')))
print('apple pies '+str(a(allguess, 'apple pies')))
可是没有用到k,我改成了这样
allguess={'1':{'apples':5,'pretzeles':12},
'2':{'ham sandwiches':3,'apples':2},
'3':{'cups':3,'apple pies':1}}
def a(guests,item):
numbrount=0
for v in guests.values():
numbrount=numbrount+v.get(item,0)
return numbrount
print('number of things being brought:')
print('apples '+str(a(allguess, 'apples')))
print('cups '+str(a(allguess, 'cups')))
print('cakes '+str(a(allguess, 'cakes')))
print('ham sandwich '+str(a(allguess, 'ham sandwiches')))
print('apple pies '+str(a(allguess, 'apple pies')))
有什么弊端吗? 没有 那除了这样,难道还有别的更加简便的把字典的键和值单独提取出来的方法吗?{:10_256:}
页:
[1]