Python | Initialize dictionary with None values
Last Updated :
27 Jul, 2023
Sometimes, while working with dictionaries, we might have a 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 memoization in general or competitive programming. Let's discuss certain ways in which this task can be performed.
Initialize dictionary with None values 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
# 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))
OutputThe dictionary with None values : {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Time Complexity: O(n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list
Initialize dictionary with None values 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
# 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))
OutputThe dictionary with None values : {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Initialize dictionary with None values Using dict() and enumerate
In this method, we use the built-in function enumerate() which returns an iterator that produces tuples containing the index and the value of the elements in an iterable. We use repeat(None, 10) which returns an iterator that repeats the value None 10 times. We then pass these tuples to the dict() constructor to create the dictionary with keys being the indexes and values being None.
Python3
# Python3 code to demonstrate working of
# Initialize dictionary with None values
# Using dict() and enumerate
from itertools import repeat
# Using dict() and enumerate
# Initialize dictionary with None values
res = dict(enumerate(repeat(None, 10)))
# printing result
print("The dictionary with None values : " + str(res))
# This code is contributed by Edula Vinay Kumar Reddy
OutputThe dictionary with None values : {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Time complexity: O(n)
Auxiliary Space: O(n)
Initialize dictionary with None values Using a loop and update ()
Algorithm:
- Initialize variable n to 10.
- Initialize an empty dictionary res.
- Start a loop for n times: a. Update the dictionary res with a key-value pair where key is i and value is None.
- Print the dictionary res.
Python3
n = 10
res = {}
for i in range(n):
res.update({i: None})
print("The dictionary with None values : " + str(res))
OutputThe dictionary with None values : {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Time complexity: O(n) The loop iterates n times, where n is the size of the input, so the time complexity is O(n).
Auxiliary Space: O(n) The dictionary res stores n key-value pairs, so the space complexity is O(n).
Initialize dictionary with None values Using a dictionary comprehension
Step-by-step approach:
- The code uses a dictionary comprehension to create a new dictionary named 'res'.
- The dictionary comprehension iterates over a range of 10 numbers using the 'range()' function.
- For each number in the range, a new key-value pair is created in the 'res' dictionary. The key is the current number from the range, and the value is set to None.
- Finally, the resulting dictionary is printed using the 'print()' function.
Below is the implementation of the above approach:
Python3
# Using a dictionary comprehension
res = {i: None for i in range(10)}
# printing result
print("The dictionary with None values : " + str(res))
OutputThe dictionary with None values : {0: None, 1: None, 2: None, 3: None, 4: None, 5: None, 6: None, 7: None, 8: None, 9: None}
Time complexity: O(n), where n is the number of elements in the range.
Auxiliary space: O(n), where n is the number of elements in the range. This is because the dictionary stores n key-value pairs.
Similar Reads
Python Tutorial | Learn Python Programming Language Python Tutorial â Python is one of the most popular programming languages. Itâs simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly.Python is:A high-level language, used in web development, data science, automatio
10 min read
Python Interview Questions and Answers Python is the most used language in top companies such as Intel, IBM, NASA, Pixar, Netflix, Facebook, JP Morgan Chase, Spotify and many more because of its simplicity and powerful libraries. To crack their Online Assessment and Interview Rounds as a Python developer, we need to master important Pyth
15+ min read
Python OOPs Concepts Object Oriented Programming is a fundamental concept in Python, empowering developers to build modular, maintainable, and scalable applications. By understanding the core OOP principles (classes, objects, inheritance, encapsulation, polymorphism, and abstraction), programmers can leverage the full p
11 min read
Python Projects - Beginner to Advanced Python is one of the most popular programming languages due to its simplicity, versatility, and supportive community. Whether youâre a beginner eager to learn the basics or an experienced programmer looking to challenge your skills, there are countless Python projects to help you grow.Hereâs a list
10 min read
Python Exercise with Practice Questions and Solutions Python Exercise for Beginner: Practice makes perfect in everything, and this is especially true when learning Python. If you're a beginner, regularly practicing Python exercises will build your confidence and sharpen your skills. To help you improve, try these Python exercises with solutions to test
9 min read
Python Programs Practice with Python program examples is always a good choice to scale up your logical understanding and programming skills and this article will provide you with the best sets of Python code examples.The below Python section contains a wide collection of Python programming examples. These Python co
11 min read
Enumerate() in Python enumerate() function adds a counter to each item in a list or other iterable. It turns the iterable into something we can loop through, where each item comes with its number (starting from 0 by default). We can also turn it into a list of (number, item) pairs using list().Let's look at a simple exam
3 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Input and Output in Python Understanding input and output operations is fundamental to Python programming. With the print() function, we can display output in various formats, while the input() function enables interaction with users by gathering input during program execution. Taking input in PythonPython input() function is
8 min read