Usage of defaultdict in python: pythondefaultdict
First recognized by defaultdict
Previously, when using dictionaries, they were relatively casual, but simply using dict.
However, if a KeyError occurs when a non-existent key is used, defaultdict should be launched.
How to Use defaultdict
Yes.
from collections import defaultdictd1 = defaultdict(int)
Or
import collectionsd1 = collections.defaultdict(int)
Difference between ultdict and dict instantiation dictionary types
If defaultdict is used for any undefined key, a default value based on the method_factory parameter is returned by default. In the same case, dict () returns KeyError.
Compare the following code:
d1 = dict()d2 = defaultdict(list)print(d1['a'])print(d2['a'])
Defaultdict Construction
The official python document defines defaultdict as follows:
class collections.defaultdict([default_factory[, ...]])
The official python document explains defaultdict as follows:
defaultdicdict subclass that calls a factory function to supply missing values
Default_factory receives a factory function as a parameter, such as int str list set.
Defaultdict adds a missing (key) Method Based on dict. When a non-stored key is called, defaultdict calls _ missing __and returns a default value based on the default_factory parameter, therefore, Keyerror is not returned.
Example
Example 1
s = 'mississippi'd = defaultdict(int)for k in s: d[k] += 1print(d)
Example 2
s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]d = defaultdict(set)for k, v in s: d[k].add(v)print(d)
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.