首页 > 其他分享 >totaoBrought()读取嵌套字典列表内容

totaoBrought()读取嵌套字典列表内容

时间:2023-02-15 19:33:58浏览次数:31  
标签:totaoBrought 读取 allGuests 嵌套 num str print total apple

allGuests={'Alice':{'apples':5,'pretzels':12},
           'Bob':{'ham sandwiches':3,'apples':2},
           'Carol':{'cups':3,'apple pies':1}}

def total(x,y):
    num=0
    for k,v in x.items():
        num=num+v.get(y,0)
    return num

print('Number of things being brought: ')
print('-Apples '+str(total(allGuests,'apples')))
print('-Cups '+str(total(allGuests,'cups')))
print('-Cakes '+str(total(allGuests,'cakes')))
print('-Pretzels '+str(total(allGuests,'pretzels')))
print('-ham sandwiches '+str(total(allGuests,'ham sandwiches')))
print('-apple pies '+str(total(allGuests,'apple pies')))


Number of things being brought: 
-Apples 7
-Cups 3
-Cakes 0
-Pretzels 12
-ham sandwiches 3
-apple pies 1

 

标签:totaoBrought,读取,allGuests,嵌套,num,str,print,total,apple
From: https://www.cnblogs.com/lucass/p/17124416.html

相关文章