Example of using the Python standard library defaultdict module

Source: Internet
Author: User
This article describes how to use the defaultdict module in the Python standard library. This article describes how to use defaultdict to add the default type to the value element of the dictionary and two use cases of defaultdict, you can refer to collections in the Python standard library to perform 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, it is good to look at it more.
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:

The code is as follows:


Import collections as coll

Def default_factory ():
Return 'default value'

D = coll. defaultdict (default_factory, foo = 'bar ')
Print 'd: ', d
Print '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:

The code is as follows:


D: defaultdict ( , {'Foo': 'bar '})
Foo => bar
Foo => 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

The code is as follows:


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 ['key'] = set ()
Dict_set1 ['key']. add ('20140901 ')
Dict_set1 ['key']. add ('000 ')
Print dict_set1


If defaultdict is used

The code is as follows:


Dict_set = coll. defaultdict (set)
Dict_set ['key']. add ('000 ')
Dict_set ['key']. add ('20140901 ')
Print dict_set

The advantage is that you do not need to perform the set initialization judgment.

Two small cases

The code is as follows:


Ss = '000000'
Dict_int = coll. defaultdict (int)
For s in ss:
Dict_int [s] + = 1
Print dict_int

'''''
The example in the official document shows that this method is simple.
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.