码迷,mamicode.com
首页 > 其他好文 > 详细

构造字典

时间:2017-06-15 21:47:07      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:遍历   dict   字典   bsp   for   new   app   判断   大于等于   

有一个列表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

 

构造字典

标签:遍历   dict   字典   bsp   for   new   app   判断   大于等于   

原文地址:http://www.cnblogs.com/winter1519/p/7019914.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!