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