python的item方法_Python 字典方法(.get .item)

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:3

for 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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值