构造字典

有一个列表values=[1,3,5,7,9,12,56,98,23,77,67,87,99,4,3,43,54,23],请构造一个字典,当值小于50时key为small,当值大于等于50时key为big。

方法一:

dic = {}   #定义一个空的字典
values=[1,3,5,7,9,12,56,98,23,77,67,87,99,4,3,43,54,23]
for i in values: #对字典进行遍历
if i < 50 :
if 'small' in dic.keys(): #判断small这个key是否在字典中
dic['small'].append(i)
else:
dic['small']=[i]
else:
if 'big' in dic.keys():
dic['big'].append(i)
else:
dic['big']=[i]
print("The new dictionary is %s" % dic)

The new dictionary is {'small': [1, 3, 5, 7, 9, 12, 23, 4, 3, 43, 23], 'big': [56, 98, 77, 67, 87, 99, 54]}

 

方法二:

import collections
dic = collections.defaultdict(list) #定义一个字典,默认是列表
values=[1,3,5,7,9,12,56,98,23,77,67,87,99,4,3,43,54,23]
for i in values:
if i < 50:
dic['small'].append(i)
else:
dic['big'].append(i)
print("The new dictionary is %s" % dic)

The new dictionary is defaultdict(<class 'list'>, {'small': [1, 3, 5, 7, 9, 12, 23, 4, 3, 43, 23], 'big': [56, 98, 77, 67, 87, 99, 54]})

 

以上两种方法仅供参考,有需要的朋友可以看一下,共同探讨共同进步。

QQ:1127000483

 

posted @ 2017-06-15 20:33  winterforever  阅读(458)  评论(0编辑  收藏  举报