Python Create Dictionary with Integer
Last Updated :
25 Jan, 2024
There sometimes comes a problem with how to initialize a dictionary in Python with 0 but what does this mean? In reality, it is just to create a dictionary where all the values are set to 0. The keys can be any desired set of keys, but the values associated with these keys will all be 0 initially. In this article, we will see how to create a dictionary with zeros in Python.
Create a Dictionary with Integer in Python
There are different methods to Create a Dictionary with Zeros in Python. Below we are explaining all the possible approaches with proper practical implementation.
- Initialize a Python dictionary with zero using basic dict initialization.
- Using a for-loop
- Using Dictionary Comprehension
- Using dict.fromkeys() Method
- Using collections.defaultdict()
Initialize a Python Dictionary with Integer
One of the most easiest ways is just to initialize dictionary with 0 is by using curly braces {} and putting all the values manually. However this method has a big disadvantage in that it does not work for many values.
Python3
my_dict = { 'apple' : 0 , 'banana' : 0 , 'orange' : 0 }
print (my_dict)
|
Output
{'apple': 0, 'banana': 0, 'orange': 0}
Create Dictionary with Integer Using a for loop
In this example, we are using a for loop to initialize dictionary Python to 0.
Python3
keys = [ 'apple' , 'banana' , 'orange' ]
my_dict = {}
for i in range ( len (keys)):
my_dict[keys[i]] = 0
print (my_dict)
|
Output
{'apple': 0, 'banana': 0, 'orange': 0}
Create Dictionary with Zeros Using Dictionary Comprehension
In this method we utilize a dictionary comprehension to create a dictionary with specified keys and all values initialized to zero.
Python3
keys = [ 'apple' , 'banana' , 'orange' ]
my_dict = {key: 0 for key in keys}
print (my_dict)
|
Output
{'apple': 0, 'banana': 0, 'orange': 0}
Initialize a Python Dictionary with Zero Using dict.fromkeys() Method
The dict.fromkeys() method is a built-in method to python initialize dict with zero.It creates a new dictionary with keys from the provided iterable and sets all corresponding values to the specified default value.
Python3
keys = [ 'apple' , 'banana' , 'orange' ]
default_value = 0
my_dict = dict .fromkeys(keys, default_value)
print (my_dict)
|
Output
{'apple': 0, 'banana': 0, 'orange': 0}
Create Dictionary with Integer Using collections.defaultdict()
In this method, we used collections.defaultdict to create a dictionary with zeros, where the default value for any non-existing key is set to zero, streamlining the initialization process.
Python3
from collections import defaultdict
size = 5
zero_dict = defaultdict( int , {i: 0 for i in range (size)})
print ( zero_dict)
|
Output
defaultdict(<class 'int'>, {0: 0, 1: 0, 2: 0, 3: 0, 4: 0})
Share your thoughts in the comments
Please Login to comment...