Home >Backend Development >Python Tutorial >PythonTipsandTraps(二)
6. The collections module also provides OrderedDict, which is used to obtain ordered dictionaries
import collections
d = {'b':3, 'a':1,'x':4,'z':2}
dd = collections.OrderedDict(d)for key, value in dd.items(): PRint key, value#b 3#a 1#x 4#z 2
7. The defaultdict module of collections module
defaultdict class is like is a dict, but it is initialized using a type (it can also be a callable function with no parameters, the function returns the result as a default value), it accepts a type as a parameter, and can instantiate a value when the accessed key does not exist As default
import collections
aa = collections.defaultdict(list)
aa['a']# []aa['b'].append(1)print aa['b']# [1]
The above is the content of PythonTipsandTraps (2). For more related content, please pay attention to the PHP Chinese website (www.php.cn)!