Original address: http://www.cnblogs.com/herbert/archive/2013/01/09/2852843.html
The author first looked at Defaultdict's help explanation, the author read the explanation and translated the English translation out, found still can not understand.
The latter is understood directly by looking at the example. Find the author is very humorous.
Posted below,defaultdict(), SetDefault and normal {} code
Compared to defaultdict and setdefault , the efficiency ofdefaultdict is higher.
The normal {} can only be assigned (because you will not find the key if you append the operation directly)
ImportCollectionss= [('Yellow', 1), ('Blue', 2), ('Yellow', 3), ('Blue', 4), ('Red', 1)]#defaultdictD =collections.defaultdict (list) forKvinchS:d[k].append (v) # D results for {' Blue ': [2, 4], ' Red ': [1], ' yellow ': [1, 3]
#Use dict and SetDefaultg = {} forKvinchS:g.setdefault (k, []). Append (v) # G The result is {' Blue ': [2, 4], ' Red ': [1], ' yellow ': [1, 3]}#Use dictE = {} forKvinchS:e[k]=V
# e result {' Blue ': 4, ' Red ': 1, ' Yellow ': 3}
About Python's defaultdict