[Python-tools] defaultdict application scenarios
In the Python standard library, collections performs a lot of expansion operations on the data structure of the set type. These operations will bring a lot of convenience when we use the set.
Defaultdict is one of the methods, that is, to add the default type to the value element of the dictionary. I have seen it before but did not pay attention to how to use it. Today I have taken a special look.
The first example is introduced in various major articles:
Import collections as colldef default_factory (): return 'default value' d = coll. defaultdict (default_factory, foo = 'bar') print 'd: ', dprint 'foo =>', d ['foo'] print 'foo => ', d ['bar'] # The element whose key is 'bar' does not exist and has a default value.
The output result is as follows:
d: defaultdict(
, {'foo': 'bar'})foo=> barfoo=> default value
Conclusion: we can see that when we take an unused key in the dictionary, a value is automatically generated based on default_factory, similar to d. get ('bar', 'default value ')
A comparison example:
If the value of a map in a dictionary is a set, add two elements to the set consecutively. The original dict
Dict_set1 = {}# if you do not know whether the key in this field exists, you must first determine if 'key' not in dict_set1: dict_set1 = set () dict_set1 ['key']. add ('20140901') dict_set1 ['key']. add ('000') print dict_set1
If defaultdict is used
dict_set = coll.defaultdict(set)dict_set['key'].add('000')dict_set['key'].add('111')print dict_set
The advantage is that you do not need to perform the set initialization judgment.
Two small cases
Ss = '000000' dict _ int = coll. defaultdict (int) for s in ss: dict_int [s] + = 1 print dict_int ''' this example of the official documentation can see this write concise https://docs.python.org/2/library/collections.html#collections.defaultdict >>>> s = [('yellow', 1 ), ('Blue ', 2), ('yellow', 3), ('Blue', 4), ('red', 1)] >>> d = defaultdict (list) >>> for k, v in s :... d [k]. append (v)... >>> d. items () [('blue', [2, 4]), ('red', [1]), ('yellow', [1, 3])] '''
This object is useful when we perform this statistical data operation.
This article is from the "orangleliu notebook" blog, please be sure to keep this http://blog.csdn.net/orangleliu/article/details/38669867