How To Initialize Dictionary With Default Values In Python

In Python, a dictionary is a collection of key-value pairs, where each key is associated with a certain value. Although dictionaries are mutable, sometimes a situation arises where we would like to initialize a dictionary with default values.

In this tutorial, we will learn how to initialize a dictionary with default values in Python using various methods such as the dict.fromkeys() method, a dictionary comprehension, and the collections.defaultdict class.

Using dict.fromkeys()

The dict.fromkeys() method is a built-in Python method that can be used to create dictionaries from a list or tuple. By specifying a default value as a second argument, you can initialize a dictionary with default values. The syntax for dict.fromkeys() is as follows:

For example, let’s create a dictionary with keys ‘apple’, ‘orange’, and ‘banana’, and initialize the values to 0:

{'apple': 0, 'orange': 0, 'banana': 0}

Using Dictionary Comprehension

A dictionary comprehension is another way to create a dictionary with default values. It uses a more concise syntax compared to dict.fromkeys(). The syntax for dictionary comprehension is as follows:

Let’s create the same dictionary as in the previous example using dictionary comprehension:

{'apple': 0, 'orange': 0, 'banana': 0}

Using collections.defaultdict

The collections.defaultdict class is a part of the collections module and can be used to create a dictionary initialized with default values. The syntax for collections.defaultdict is as follows:

Here, the default_value_factory is a function that returns a default value when called. Let’s create the same dictionary as in the previous examples using collections.defaultdict:

{'apple': 0, 'orange': 0, 'banana': 0}

Full Code

Output:

{'apple': 0, 'orange': 0, 'banana': 0}
{'apple': 0, 'orange': 0, 'banana': 0}
{'apple': 0, 'orange': 0, 'banana': 0}

Conclusion

In this tutorial, we have learned three different ways to initialize a dictionary with default values in Python: using the dict.fromkeys() method, using dictionary comprehension, and using the collections.defaultdict class. Each of these methods has its own advantages and use cases, so choose the one most suitable for your specific needs.