天天看点

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

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