Python defaultdict() will allow us to create a default value for dict data type. Meanwhile, you may find the code:
result = defaultdict(list)
In this tutorial, we will use some examples to help you understand it.
Python defaultdict()
Python defaultdict() can create a default diction using a factory function.
dict =defaultdict( factory_function)
The factory_function can be list, set, str et al.
When we read an nonexistent key, it will read a default value by factory_function. Here is an example:
from collections import defaultdict dict1 = defaultdict(int) dict2 = defaultdict(set) dict3 = defaultdict(str) dict4 = defaultdict(list) dict1[2] ='two' print(dict1[1]) print(dict2[1]) print(dict3[1]) print(dict4[1])
Run this code, you will see result:
0 set() []
What is defaultdict(list)?
defaultdict(list) means will create a diction data with default value [].
We can append a new value to a key directly.
Here is an example:
from collections import defaultdict dict = defaultdict(list) dict['name'].append("Tom") dict['name'].append("Lily") dict['name'].append("Kate") print(dict)
Run this code, you will see:
defaultdict(<class 'list'>, {'name': ['Tom', 'Lily', 'Kate']})
In this code, we append new name to dict[‘name’] without checking key ‘name‘ is existing or not.