Home  >  Article  >  Backend Development  >  PythonTipsandTraps(二)

PythonTipsandTraps(二)

黄舟
黄舟Original
2016-12-20 17:19:12868browse

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)!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:PythonTipsandTraps(一)Next article:PythonTipsandTraps(一)