How to convert a defaultdict to dict in Python

How to convert a defaultdict to dict in Python

In Python, the defaultdict class from the collections module gives an easy way to handle missing keys by assigning a default value to them. However, there might be situations where you need to convert a defaultdict to a regular dict object. In this blog post, we will explore a simple and effective way to perform this conversion.

To convert a defaultdict to dict in Python, use dict(default_dict). It creates a new dict with the same key-value pairs. The resulting dict will lose the default behavior.

Example:

dict: {'key1': 'Learn', 'key2': 'Share'}

defaultdict : defaultdict(<class 'int'>, {'key1': 'Learn', 'key2': 'Share'})

Understanding defaultdict

Before proceeding further on the conversion from defaultdict to dict, let’s quickly recap what a defaultdict is. Similar to a regular dictionary (dict), a defaultdict is a subclass of dict. The key difference lies in the behavior when accessing a missing key. With a defaultdict, if you try to access a non-existent key, it will create that key and assign a default value specified during its creation.

Below are the examples to check the behavior of defaultdict and dict, When you tried to access a non-existent key

Regular Dictionary(dict)

Dict = {1: 'Learn', 2: 'Share', 3: 'knowledge'}
print(Dict)

#Output
{1: 'Learn', 2: 'Share', 3: 'knowledge'}

#Try to access a key which is not exist:
print(Dict['10'])

#Output
KeyError: '10'

In the above example, We could understand, In a Normal dictionary, When we try to access a nonexistent key (in this case it is ’10”), It will give you the “KeyError: ’10′”

defaultdict

default_dict = defaultdict(int)
default_dict['key1'] = 'Learn'
default_dict['key2'] = 'Share'
print(default_dict['key5'])

#Output
0

In this case, When you try to access a key that does not exist (in this case it is “key5”). default_dict will insert a default value(0) for the “key5”

Hope you understand the basic difference between the defaultdict and dict, Let’s proceed with the steps for the conversion process (defaultdict -> dict)

Convert a defaultdict to dict

To convert a defaultdict to a regular dict, we can use the built-in dict() the function in Python. This function takes an iterable or mapping as an argument and returns a new dictionary object.

Below is the procedure to convert defaultdict => dict

Step 1: Import the defaultdict class from the collections module.

from collections import defaultdict

Step 2: Create a defaultdict object and populate it with some key-value pairs.

default_dict = defaultdict(int)
default_dict['key1'] = 'Learn'
default_dict['key2'] = 'Share'

Step 3: Use the dict() function to convert the defaultdict to a regular dict.

regular_dict = dict(default_dict)

By calling dict(default_dict), we pass the defaultdict object as an argument to the dict() function, which creates a new dictionary with the same key-value pairs. The resulting regular_dict will no longer have the default behavior of defaultdict and will behave like a standard dict object.

Complete Code

from collections import defaultdict

default_dict = defaultdict(int)
default_dict['key1'] = 'Learn'
default_dict['key2'] = 'Share'

regular_dict = dict(default_dict)

print(regular_dict)
print(default_dict)

Output:

regular_dict:
{'key1': 'Learn', 'key2': 'Share'}

default_dict:
defaultdict(<class 'int'>, {'key1': 'Learn', 'key2': 'Share'})

In this above code, we first import the defaultdict class from the collections module. Then, we create a defaultdict object with string values and assign some key-value pairs to it. Then, by using the dict() function, we converted the default_dict to a regular dict. The resulting regular_dict contains the same key-value pairs as the original default_dict which is shown in the output.

Conclusion:

In Conclusion, It is a straightforward process to convert a defaultdict to a regular dict in Python. By using the dict() function, we can easily remove the default behavior and obtain a standard dict object. This conversion can be helpful when you no longer require the automatic creation of missing keys with default values.

Good Luck with your Learning !!

Related Topics:

Random Word Generator Python

How to Find N Root of a Number – Python

Python Create Directory If It Doesn’t Exist

Jerry Richard R
Follow me