Initialize an Empty Dictionary in Python
Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized.
Now, Let’s see the different ways to create an Empty Dictionary.
Method 1: Use of { } symbol.
We can create an empty dictionary object by giving no elements in curly brackets in the assignment statement
Code:
Python3
emptyDict = {}
print (emptyDict)
print ( "Length:" , len (emptyDict))
print ( type (emptyDict))
|
Output
{}
Length: 0
<class 'dict'>
Method 2: Use of dict() built-in function.
Empty dictionary is also created by dict() built-in function without any arguments.
Code:
Python3
emptyDict = dict ()
print (emptyDict)
print ( "Length:" , len (emptyDict))
print ( type (emptyDict))
|
Output
{}
Length: 0
<class 'dict'>
Method 3 : initialize a dictionary
Step-by-Step approach:
- Initializes an empty dictionary named ’emptyDict’.
- Initialize the ’emptyDict’ dictionary. A dictionary comprehension is a concise way to create a dictionary in Python, using a single line of code. In this case, the comprehension is empty because there are no key-value pairs to iterate over. Therefore, an empty list is passed to comprehension. A result is an empty dictionary.
- Print the resulting dictionary.
- Print the length of the dictionary using the ‘len()’ function and the type of the dictionary using the ‘type()’ function.
Python3
emptyDict = {key: value for key, value in []}
print (emptyDict)
print ( "Length:" , len (emptyDict))
print ( type (emptyDict))
|
Output
{}
Length: 0
<class 'dict'>
TIme Complexity: The time complexity of this method is O(1) because we are initializing an empty dictionary using dictionary comprehension, which takes constant time.
Space Complexity: The space complexity of this method is also O(1) because we are initializing an empty dictionary that takes up a fixed amount of space in memory, regardless of the size of the dictionary.
Last Updated :
09 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...