有序字典(OrderedDict)、默认字典(defaultdict)内置函数

 http://www.cnblogs.com/wupeiqi/articles/5115190.html

import collections
do = collections.OrderedDict()
do['k1']=10
do['k2']=20
do.pop('k2')
print do

 

import collections
from collections import defaultdict
d1 = defaultdict(list)
s = [('yellow', 1), ('blue', 2), ('yellow', 3), ('blue', 4), ('red', 1)]

for k,v in s:
    d1[k].append(v)
print d1 #返回{'blue': [2, 4], 'red': [1], 'yellow': [1, 3]})
print d1['blue']
print list(d1) #返回['blue', 'red', 'yellow']
print list(d1.items()) #返回[('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])]

d2=defaultdict(int)
print d2['k1'] #返回0。int初始化默认值为0

 

posted on 2016-05-03 15:52  momingliu11  阅读(878)  评论(0编辑  收藏  举报