天天看點

有序字典(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