How to Initialize Dictionary with Default Values

In this Python tutorial, I will explain several methods for initializing a dictionary with default values.

While analysing the dataset based on the log files, I wanted to count the occurrences of various times, such as product IDs in a sales log. To simplify the counting logic. I had to initialize the dictionary with a default value of 0 for each key in the dataset.

I used the for-loop method to initialize the dictionary with default values. In this tutorial, I explained the for-loop method. Additionally, I have explained two other methods that you may prefer.

Finally, I have explained why you must initialize the dictionary with default values.

Python Initialize Dictionary with Default Value

First, let me tell you, “What dictionary is?” A dictionary is a container containing a collection of values. The dictionary stores this collection of values in a specific format, like ‘{key:value}’. The item before the colon (:) is called a key, and the item after the colon is called the value.

For example, you can represent real-world information in a dictionary. Suppose you have a product with a name and price, so here you can use the product name as the key and its price as value, like this {laptop:20000}, each dictionary item is referred to as a key-value pair.

So, the dictionary currently contains one item, but you can include multiple key-value pairs, as I told you, it can contain multiple key-value pairs. What happens if you remove the key-value pair from the dictionary? It becomes an empty dictionary.

READ:  Isdigit method in String Python

The empty dictionary is represented using curly braces like this { }. Now, suppose you have an empty dictionary.

How are you going to insert the key-value pair? When you create an empty dictionary and insert the key-value pair, this process is called initializing the dictionary with default values.

So, creating and inserting the initial key value into the dictionary is called initialization of the dictionary. There are several methods to initialise the dictionary with a default value, which I will explain soon.

Python Create Dict with Default Value Using {}

To initialise the dictionary with {}, add some key value while creating, as shown in the code below.

products ={"Laptop": "Electronics","Jeans": "Clothing", "Smartphone": "Electronics", "Sweater": "Clothing"}

print(products)
Python Create Dict with Default Value Using {}.JPG

Look at the above picture, which shows a new dictionary ‘products’ being created and initialized with default values: the product name and its type; for example, the product name is ‘Laptop’, and its type is ‘Electronic’, the dictionary is initialized with four default values.

So, while creating a dictionary using curly braces {}, insert the key-value part simultaneously.

Python Initialize Dictionary Using dict() Function

Python provides a method called dict(), which you can use to create a new dictionary; it takes a key-value pair as you provide to the {}; if you don’t provide any key value to it, it creates an empty dictionary.

So, if you provide the value, it creates and initializes with the given key-value pair.

For example, you can create a dictionary to store user information and initialize it with default values. Look at and run the code below.

user = dict(username='jenny', age=30, email='jenny@icloud.com')

print(user)
Python Initialize Dictionary Using dict() Function.JPG

Look at the above picture, where you provided the user with individual information as a key-value to the dict() method; this dict() takes those key-value pairs, creates a new dictionary, and initializes the dictionary with the given values.

READ:  How to remove decimals from a string in Python [4 Methods]

As a result, the dictionary contains the initialized value, {‘username’: ‘jenny’, ‘age’: 30, ’email’: ‘jenny@icloud.com’}.

So, pass the data to the dict() method. It creates and initializes the dictionary with the key-value pair.

This is how you can use Python’s dict() method to provide the dictionary’s initial value.

Python init Dict with Default Value Using For Loop

You can even initialize the dictionary with the default value using the for loop; the simple logic is that the loop will iterate over another list, and then, taking value from the list, it initialises the empty dictionary.

For example, consider that you have a list of American cities and another list of the respective states where each town is located. You want to create a dictionary in Python where each city (key) points to its state (value).

cities = [‘Chicago’, ‘Los Angeles’, ‘Houston’, ‘Phoenix’, ‘Philadelphia’]

states = [‘Illinois’, ‘California’, ‘Texas’, ‘Arizona’, ‘Pennsylvania’]

city_with_state = {}

for i in range(len(cities)):

    city_with_state[cities[i]] = states[i]

print(city_with_state)

Python init Dict with Default Value Using For Loop

Look at the output; the loop initializes the city_with_state dictionary using the list of cities and states values.

Let’s understand how it works. The first two lists are cities and states, where cities act as the key and states act as the dictionary’s value.

The new empty dictionary uses the ‘city_with_state = {}’ code. Then, using the ‘for i in range(len(cities)):’, Iterating over the list where ‘i’ in the loop represents the index value of items in the list.

Using this index, ‘i’, the first value from the list of cities is taken using the cities[i], and then it passes it to the empty dictionary as city_with_stat[cities[i]] to create a key. Then, the value is associated with this key by assigning the values from the list states using the ‘=states[i]’.

READ:  How to extract all values from a dictionary in Python

In the same way, in each iteration, each value from the list of cities and states is taken as a key and value, respectively, and then the empty dictionary is initialized using these key-value pairs.

As result, a new dictionary is created and initialised with default values like {‘Chicago’: ‘Illinois’, ‘Los Angeles’: ‘California’, ‘Houston’: ‘Texas’, ‘Phoenix’: ‘Arizona’, ‘Philadelphia’: ‘Pennsylvania’}.

Before ending this tutorial, I want to explain why you must initialise the dictionary with default values.

  • Avoiding Key Errors: By pre-initializing a dictionary with specific keys, we can prevent potential KeyError exceptions in Python when trying to access keys that might not be present if added dynamically.
  • Data Integrity: Initializing Python dictionaries with keys and values can serve as documentation. A developer or user looking at the dictionary can instantly understand its intended structure and the kind of data it should store.
  • Default Values: When we initialize a Python dictionary with keys and values, we often set default values for those keys. This can be helpful in scenarios where we need to ensure every key has some initial value, which can then be updated or modified based on subsequent operations.

I hope you understand how to initialize a dictionary with default values from the above examples.

Conclusion

In this Python tutorial, you learned how to initialize a dictionary with default values using the for loop, curly braces{} and dict() methods.

You may like to read: