Defaultdict in PythonThe dictionary is an unordered collection of data values in Python used for storing data values such as maps. The dictionary holds key-value pairs instead of holding a single value as an element like other data types. The key implemented in the dictionary must be unique and immutable. That is, the Python tuple can be a key, but the Python list cannot be a key in the dictionary. We can create a dictionary by placing a sequence of elements inside the curly brackets {}, a comma “,” can separate the values. Example 1:Output: Dictionary: {1: 'A', 2: 'B', 3: 'C', 4: 'D'} key pair 1: A key pair 3: C But if we try to print the 5th key value then, we will get the error because “Dict_1” does not contain the 5th key value. Example 2:Output: Dictionary: {1: 'A', 2: 'B', 3: 'C', 4: 'D'} --------------------------------------------------------------------------- KeyError Traceback (most recent call last) Whenever the keyError is raised, it may become a problem for the users. We can overcome this error by using another dictionary of Python, which is like a container known as Defaultdict. The users can find this dictionary inside the ‘collections’ module. defaultdictThe defaultdict is a dictionary of Python, which is like a container present inside the ‘collections’ module. It is a sub-class of the dictionary class which is used for returning the dictionary-like object. Both defaultdict and dictionary have the same functionality, except defaultdict never raise any KeyError as it provides a default value for the Key, which does not exist in the dictionary created by the user. Syntax: Parameters:
Example: Output: Dictionary: defaultdict( Inner Working of defaultdictWhen we use defaultdict, we get an additional writable instance variable and one method in addition to the standard dictionary operations. The writable instance variable is the default_factory parameter and __missing__ is the method.
Example: Output: Dictionary: defaultdict(
Example: Output: Dictionary: defaultdict( How to Use “List” as default_factoryWe can pass a list class as the default_factory argument, and it will create a defaultdict with the values that are set in list format. Example: Output: Dictionary with values as list: defaultdict(<class 'list'>, {7: [7], 8: [8], 9: [9], 10: [10], 11: [11]}) How to Use “int” as default_factoryWe can pass the int class as the default_factory argument, and it will create a defaultdict with the default value set as zero. Example: Output: defaultdict(<class 'int'>, {1: 2, 2: 3, 3: 1, 4: 2}) ConclusionIn this tutorial, we have discussed defaultdict in Python and how we can perform different operations on defaultdict by using the default_factory parameter. |
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/263409.html