for 循环 与 python dicts 类

python  dict 入门

# example of use for loop to create a dicts
myset = set(['a', 'b', 'c', 'd'])
mydict = {item: (yield ''.join([item, 's'])) for item in myset}


dicts ={}
stocks = ['d','c','b','a']
keys = range(4)

# examples of using for loop to create a dicts
for i in stocks:
    print('1: %s',i)
    
for i in range(len(stocks)):
    dicts[i] = stocks[i]
print('2:',stocks[i])
    
for i in keys:
    dicts[i] = stocks[i]
print('3:',dicts)
    
# example 1 create a dicts 
dicts ={}
def one_to_three_doubles():
    for num in range(1, 4):
        yield {
            num:num * 2
        }
i = 0
for item in one_to_three_doubles():
    dicts[i] = item
    i +=1
print('4:',(dicts.keys(),dicts.values()))       
    
        
# example 2 

dicts ={}
def one_to_three_doubles():
    for num in range(1, 4):
        yield {
            num,num * 2
        }

tally = defaultdict(int)
for k,v in one_to_three_doubles():
    tally[k] += v   
print ('5:',tally[2])

# example check not None
dicts1 = {'a':None}
dicts2 = {}
if not dicts1['a'] is None:
    print ('6:',dicts1.values())
if dicts2.values() is not None:
    print ('dicts2 is not None,but dicts2 lens is:',len(dicts2.values()))   

输出结果如下

1: %s d
1: %s c
1: %s b
1: %s a
2: a
3: {0: 'd', 1: 'c', 2: 'b', 3: 'a'}
4: (dict_keys([0, 1, 2]), dict_values([{1: 2}, {2: 4}, {3: 6}]))
5: 4
dicts2 is not None,but dicts2 lens is: 0
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值