Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article has participated in the “Digitalstar Project” and won a creative gift package to challenge the creative incentive money. Defaultdict is a subclass of dict. The first argument provides an initial value for the default_factory property, which defaults to None. It overrides a method and adds a writable instance variable. Other functions are the same as regular dict, but default values are provided for non-existent keys to avoid KeyError exceptions.

The use of single-valued mapping dictionaries

1.1 Initialization Situation

Let’s take a look at a normal dictionary before we initialize it

Regular dict causes KeyError exceptions

count = {}
count['apple']
count['cherry']
print(count)
Copy the code

result:

Traceback (most recent call last):
  File "D:/interview/interview/22.py", line 2, in <module>
    count['apple']
KeyError: 'apple'
Copy the code

1.1.1 Type Name as initialization parameter

from collections import defaultdict
​
count = defaultdict(int)
count['apple']
count['cherry']
print(count)
Copy the code

result:

defaultdict(<class 'int'>, {'apple': 0, 'cherry': 0})
Copy the code

1.1.2 Callable functions as initialization parameters

def zero():
    return 0
​
​
count = defaultdict(zero)
count['apple']
count['cherry']
print(count)
Copy the code

result:

defaultdict(<function zero at 0x0000020D4DE55048>, {'apple': 0, 'cherry': 0})
Copy the code

1.2 The situation during the update

Inherits all the methods of the dictionary. The default dictionary must specify a default value for the dictionary when initialized

from collections import defaultdict
​
dic = defaultdict(dict)
dic["k1"].update({"asdsa":"123"})
print(dic)
Copy the code

result:

defaultdict(<class 'dict'>, {'k1': {'asdsa': '123'}})
Copy the code

The dictionary DIC is defined as a dictionary type, so the dictionary update method can be performed even if there is no key k1 in the dictionary. This operation would result in an error in a normal dictionary

Case of multivalued mapping dictionary

In general, a dictionary is a mapping of one key to one value. If you want to map multiple values to one key, you can put multiple values into a container.

2.1 Initialization Situation

2.1.1 Operations of a common dictionary

dict1 = {
    'a': [1, 2, 3],
    'b': [4, 5]
}
dict2 = {
    'a': {1, 2, 3},
    'b': {4, 5}
}
Copy the code

Whether you use lists or collections depends on your needs. Use lists if you want to preserve the insertion order of elements, and collections if you don’t.

2.1.2 Operations using the default dictionary

from collections import defaultdict
​
dict1 = defaultdict(list)
dict1['a'].append(1)
dict1['a'].extend([2, 3])
dict1['b'].extend([4, 5])
​
dict2 = defaultdict(set)
dict2['a'].add(1)
dict2['a'].update([2, 3])
dict2['b'].update([4, 5])
print(f'dict1===={dict1}')
print(f'dict2===={dict2}')
Copy the code

result:

dict1====defaultdict(<class 'list'>, {'a': [1, 2, 3], 'b': [4, 5]})
dict2====defaultdict(<class 'set'>, {'a': {1, 2, 3}, 'b': {4, 5}})
Copy the code

One thing to note about using DefaultDict is that it creates mapping entities (values) for keys that don’t exist. If you don’t need this feature, use the setDefault () method on a regular dictionary instead

2.1.3 Replace defaultdict with setDefault ()

dict1 = {}
dict1.setdefault('a', []).append(1)
dict1.setdefault('a', []).extend([2, 3])
dict1.setdefault('b', []).extend([4, 5])
print(f'dict1===={dict1}')
Copy the code

result:

dict1===={'a': [1, 2, 3], 'b': [4, 5]}
Copy the code

2.2 Update situation

2.2.1 Operations of a common dictionary

In general, creating a dictionary of multi-valued mappings is simple. However, choosing your own implementation can be a bit troublesome when initializing the value

d = {}
pairs = [('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2), ('banana', 4), ('pear', -1),]
for key, value in pairs:
    if key not in d:
        d[key] = []
    d[key].append(value)
print(d)
Copy the code

result:

{'banana': [3, 4], 'apple': [4], 'pear': [1, -1], 'orange': [2]}
Copy the code

2.2.2 Operations on the default dictionary

from collections import defaultdict
​
d = defaultdict(list)
pairs = [('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2), ('banana', 4), ('pear', -1),]
for key, value in pairs:
    d[key].append(value)
print(d)
Copy the code

result:

defaultdict(<class 'list'>, {'banana': [3, 4], 'apple': [4], 'pear': [1, -1], 'orange': [2]})
Copy the code

As you can see, using DefaultDict makes the code much cleaner