How to Initialize Dictionary Python with 0

In this Python tutorial, I will discuss how to initialize dictionary python with 0.

In my NLP process, I had to initialize the dictionary with 0 for each word so that I could count the frequency of each word in a text. The concept was to iterate over the text to increment the count for each word encountered.

So, to initialize the dictionary with 0, I have also used the for loop method in my project.

In this tutorial, I have explained several methods apart from the for loop, such as dictionary comprehension, assignment, dict.fromkeys(), etc.

Initialize Dictionary Python with 0

The initialize dictionary python with 0 means setting the value of each key in a dictionary to 0. In simpler words, suppose you have a dictionary containing subject scores like this {‘Math’:70,’English’:80}. After initializing it with 0, it must be like this {‘Math’:0′,English:’0′}.

There are multiple ways to do that; I will be explaining the most commonly used method.

Python Dictionary Initialize to 0 using Assignment Method

You can initialize the dictionary with 0 while creating it directly. For example, look at the code below, where dictionary keys are initialised to 0.

#Initialize each key of dictionary country_poupulation to 0 directly
country_population = {'USA':0, 'Austrailia':0, 'Canada':0}

print(country_population)
Python Dictionary Initialize to 0 using Assignment Method

Look at the output. Each key of the dictionary country_population is initialized with 0. This is a straightforward method.

This is how the Python dictionary initializes to 0 using the assignment method.

Python Dict Initialize 0 Using For Loop

To initialize the Python dictionary with 0, use the for loop to iterate over the dictionary, accessing and initializing the keys to 0 one by one.

READ:  Python dictionary length - Everything you need to know

For example, suppose you have dictionary product_price as shown below.

product_price = {'Heater':1200, 'AC':40000, 'Fan':1000}

To initialize the dictionary product_price with 0, you can use the for loop as shown below.

for key in product_price:
  product_price[key]=0

Check the value of the dictionary using the code below.

print(product_price)
Python Dict Initialize 0 Using For Loop

When you execute the above code, it initializes each key with value 0 of dictionary product_price as {‘Heater’: 0, ‘AC’: 0, ‘Fan’: 0}.

Here, in the code ‘for key in product_price’, the key represents the index of the dictionary, then product_price[key] =0 means accessing each key of the dictionary and initializing it with value 0.

Finally, print each key value of the dictionary using print(product_price).

This is how a Python dict initializes 0 using a for loop.

Python Initialize Dictionary with 0 Using Dictionary Comprehension

Dictionary comprehension means using the for loop with a dictionary, which means you will use the for loop with curly braces {} to initialize the dictionary with 0.

For example, let’s take the same dictionary product_price used in the above section. Execute the code below.

product_price = {'Heater':1200, 'AC':40000, 'Fan':1000}

dict_with_0 = {key: 0 for key in product_price}

print(dict_with_0)
Python Initialize Dictionary with 0 Using Dictionary Comprehension

In the above dictionary comprehension {key: 0 for key in product_price} as a result, it returned dictionary with initialize the value to 0 like {‘Heater’: 0, ‘AC’: 0, ‘Fan’: 0}.

Let’s understand the code part {key: 0 for key in product_price}, the key in the for loop represents each key of the dictionary product_price, and then each key value is initialised to 0 using this key:0.

This is how Python initializes a dictionary with 0 using dictionary comprehension.

Initialize the dictionary with default values of 0 using dict.fromkeys()

The dict.fromkeys() method is a built-in method. It creates a new dictionary with keys from a given sequence and values set to a specified value. So you can use this method to python initialize dict with 0.

READ:  Matplotlib 2d surface plot

For example, the city of Chicago, Illinois, is having a mayoral election. At the start of the election day, each candidate’s vote count needs to be initialized to zero. The list of candidates is known. Let’s create a dictionary and initialize it with 0.

candidates = ['Jonas', 'James', 'Chris', 'Jhony']
votes = dict.fromkeys(candidates, 0)
print(votes)
Initialize Dictionary with Default Values with 0 Using dict.fromkeys()

Look at the function dict.fromkeys() initialized each key of the dictionary candidate with the value 0. As a result, {‘Jonas’: 0, ‘James’: 0, ‘Chris’: 0, ‘Jhony’: 0}. Understand the code part dict.fromkeys(candidates, 0).

So here, the dict.fromkeys() function takes the dictionary candidates and value 0, then creates a new dictionary containing all the keys of the specified dictionary but assigns a specified value, which is 0, to each key.

This is how to initialize dictionary with default values with 0 using dict.fromkeys() function.

Python Initialize Dictionary with Default Value 0 Using Defaultdict from Collections

The defaultdict is a subclass of the built-in dict class. It overrides one method to provide a default value for a nonexistent key, which makes it another way for Python dict initialize 0:

For example, Imagine the University of Florida’s athletic department wants to maintain a record of sports equipment used by various teams.

Given the diverse range of sports, from baseball to swimming, they need a system flexible enough to accommodate any sport and its corresponding equipment, even if it’s a sport they haven’t previously tracked.

To maintain a record, dictionary equipment_inventory can be used, and its initial value should be 0, as shown below in the code.

from collections import defaultdict

equipment_inventory = defaultdict(int)

equipment_inventory['lacrosse sticks'],
equipment_inventory['footballs']
equipment_inventory['quidditch brooms']

print(equipment_inventory)
Python Initialize Dictionary with Default Value 0 Using Defaultdict from Collections

Each key of the dictionary equipment_inventory from the output is initialised with the value 0.

READ:  Python Django random number

But here, we haven’t created any dictionary with keys and values; that’s the mystery. Let’s understand the part of the code that decodes that mystery.

The line equipment_inventory = defaultdict(int) is designed to automatically initialize the missing keys with the default value 0 when you try to access them.

So here, defaultdict accepts the arguments default_factory. This default_factory is a function that sets default values for the dictionary keys. The argument int is passed to defaultdict.

That means if you try to access keys that don’t exist in the dictionary, it automatically creates a new key and initializes it with the value 0.

So, in the above code, the keys are accessed using equipment_inventory[‘lacrosse sticks’], equipment_inventory[‘footballs’], and equipment_inventory[‘quidditch brooms’]. Since these keys don’t exist, the code automatically creates and initializes them with 0.

Thus, you get the dictionary with value 0 like defaultdict(<class ‘int’>, {‘lacrosse sticks’: 0, ‘footballs’: 0, ‘quidditch brooms’: 0}).

This is how Python initializes a dictionary with a default value of 0 using defaultdict from collections.

Conclusion

In this Python tutorial, you learned how to initialize a dictionary in Python with 0 using five different methods: the assignment method, which is the basic dictionary initialization process, a for loop, dictionary comprehension, and dict.from keys; and defaultdict, with some practical examples.

You have also seen what initializing a dict in Python with zero means.

You may like to read: