Python defaultdict: 简化代码逻辑的字典子类
Python\u0027s defaultdict is a built-in container type that serves as a subclass of the dictionary (dict). Unlike regular dictionaries, defaultdict requires a default value factory function (default_factory) during initialization. This function is used to return a default value when accessing a key that doesn\u0027t exist in the dictionary. \n\nUsing defaultdict can simplify code logic, eliminating the need for additional checks and handling when accessing nonexistent keys. When accessing a nonexistent key, defaultdict automatically calls the default value factory function to create a default value and assigns it to that key. \n\nHere\u0027s an example of using defaultdict: \n\npython\nfrom collections import defaultdict \n\n# Define a default value factory function that returns an empty list \ndef default_factory(): \n return [] \n\n# Create a defaultdict and specify the default value factory function \nd = defaultdict(default_factory) \n\n# Accessing a nonexistent key returns the default value \nprint(d['key1']) # Output: [] \n\n# Adding key-value pairs to the dictionary \nd['key2'].append(1) \nd['key2'].append(2) \nd['key3'].append(3) \n\n# Accessing existing keys returns their corresponding values \nprint(d['key2']) # Output: [1, 2] \nprint(d['key3']) # Output: [3] \n \n\nIn the above example, we create a defaultdict and specify a default value factory function, default_factory, which returns an empty list. When we access a nonexistent key in the dictionary, defaultdict automatically calls the default value factory function to create an empty list and assigns it to the key. This allows us to directly append elements to the list without manually checking for the key\u0027s existence and creating the list. \n\nIt\u0027s important to note that default_factory is only called when accessing nonexistent keys through indexing. If you access a nonexistent key using the get() method, it will still return None. If you want the get() method to also return a default value, you can pass a default value as the first argument to defaultdict\u0027s constructor. For example: \n\npython\nfrom collections import defaultdict \n\n# Create a defaultdict with a default value of 0 \nd = defaultdict(int) \n\n# Accessing a nonexistent key returns the default value 0 \nprint(d['key1']) # Output: 0 \n\n# Adding key-value pairs to the dictionary \nd['key2'] += 1 \nd['key2'] += 2 \nd['key3'] += 3 \n\n# Accessing existing keys returns their corresponding values \nprint(d['key2']) # Output: 3 \nprint(d['key3']) # Output: 3 \n \n\nIn the above example, we create a defaultdict and specify a default value of 0. When accessing nonexistent keys through indexing, it will return the default value 0. This allows us to directly operate on the value corresponding to that key without manually checking for the key\u0027s existence and initializing the default value.
原文地址: https://www.cveoy.top/t/topic/qbyo 著作权归作者所有。请勿转载和采集!