Python | Initialize dictionary with None values
Sometimes, while working with dictionaries, we might have an utility in which we need to initialize a dictionary with None values, so that they can be altered later. This kind of application can occur in cases of memoizations in general or competitive programming. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using zip() + repeat()
The combination of these functions can be used to perform this particular task. In this, the None value is attached to the keys repeated using the repeat() by help of zip()
# Python3 code to demonstrate working of # Initialize dictionary with None values # Using zip() + repeat() from itertools import repeat # Using zip() + repeat() # Initialize dictionary with None values res = dict(zip(range(10), repeat(None))) # printing result print("The dictionary with None values : " + str(res)) |
The dictionary with None values : {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Method #2 : Using fromkeys()
This task can also be performed more efficiently using the inbuilt function of fromkeys() which is tailor-made for this task itself and hence recommended.
# Python3 code to demonstrate working of # Initialize dictionary with None values # Using fromkeys() # Using fromkeys() # Initialize dictionary with None values res = dict.fromkeys(range(10)) # printing result print("The dictionary with None values : " + str(res)) |
The dictionary with None values : {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Recommended Posts:
- Python | Initialize dictionary with common value
- Python | Initialize dictionary with multiple keys
- Python | Initialize a dictionary with only keys from a list
- Python dictionary | values()
- Python | Check if all values are 0 in dictionary
- Python | N largest values in dictionary
- Python | Selective key values in dictionary
- Python | Sum values for each key in nested dictionary
- Python | Max/Min of tuple dictionary values
- Python | Check for None values in given dictionary
- Python | Create a dictionary using list with none values
- Python | Get Unique values from list of dictionary
- Python | Combining values from dictionary of list
- Map function and Dictionary in Python to sum ASCII values
- Ways to extract all dictionary values | Python
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


