Details of the use of defaultdict in python

  • 2020-06-03 07:09:27
  • OfStack

I met defaultdict

When using a dictionary, I used to use dict rather loosely.
However, when an error like KeyError occurs while using a nonexistent key, it is time for defaultdict to appear.

How do I use defaultdict

It can be


from collections import defaultdict
d1 = defaultdict(int)

Or it


import collections
d1 = collections.defaultdict(int)

The difference between defaultdict and dict instantiated dictionary types

Using defaultdict any undefined key will return a default value different from the method_factory parameter by default, while dict() returns KeyError in the same case.
Compare the following code:


d1 = dict()
d2 = defaultdict(list)
print(d1['a'])
print(d2['a'])

The structure of the defaultdict

The official python document defines defaultdict as follows:


class collections.defaultdict([default_factory[, ...]])

The official python document explains defaultdict as follows:


defaultdic
dict subclass that calls a factory function to supply missing values

default_factory accepts one factory function as a parameter, such as int str list set, etc.
defaultdict adds an missing(key) method to dict. On calling the 1 unsaved key, defaultdict calls ___, 64en__, returning 1 based on the default value of the default_factory argument, so it does not return Keyerror.

Example

Example 1


s = 'mississippi'
d = defaultdict(int)
for k in s:
  d[k] += 1
print(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)


Related articles: