Defaultdict is a subclass of Dict, accepting a factory function as a parameter, and when accessing a key that does not exist in Defaultdict, the return value of the factory function is used as the default value.
class defaultdict (dict): """ defaultdict (default_factory[, ...])-Dict with default factory the default factory is called without AR Guments to produce a new value when a key was not present, in __getitem__ only. A defaultdict compares equal to a dict with the same items. All remaining arguments is treated the same as if they were passed to the Dict constructor, including keyword Argume NTS. """
Test code
Complete code: https://github.com/blackmatrix7/python-learning/blob/master/other/defaultdict.py
__author__='Blackmatrix'defFactory_func ():return 'default_factory'test_defaultdict=defaultdict (Factory_func)if __name__=='__main__': " "When a key is present, it returns the value corresponding to the key, which is no different from the normal dict." "test_defaultdict['a'] ='233333' Print(test_defaultdict['a']) " "The return value of the factory function is automatically used as the default value when accessing a nonexistent key" " Print(test_defaultdict['b']) Print(test_defaultdict['C'])
Run results
233333default_factorydefault_factory
If Defaultdict does not pass in the factory function when it is created, it throws keyerror when it accesses a nonexistent key.
from Import = defaultdict ()print(test_defaultdict2['x') # keyerror: ' x '
Python's defaultdict