Open In App

Initialize an Empty Dictionary in Python

Improve
Improve
Like Article
Like
Save
Share
Report

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




# Python3 code to demonstrate use of
# {} symbol to initialize dictionary
emptyDict = {}
 
# print dictionary
print(emptyDict)
 
# print length of dictionary
print("Length:", len(emptyDict))
 
# print type
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




# Python3 code to demonstrate use of 
# dict() built-in function to
# initialize dictionary
emptyDict = dict()
 
# print dictionary
print(emptyDict)
 
# print length of dictionary
print("Length:",len(emptyDict))
 
# print type
print(type(emptyDict))


Output

{}
Length: 0
<class 'dict'>

Method 3 :  initialize a dictionary

Step-by-Step approach:

  1. Initializes an empty dictionary named ’emptyDict’.
  2. 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.
  3. Print the resulting dictionary.
  4. Print the length of the dictionary using the ‘len()’ function and the type of the dictionary using the ‘type()’ function.

Python3




# Python3 code to demonstrate initializing
# dictionary using dictionary comprehension
 
# Using dictionary comprehension
emptyDict = {key: value for key, value in []}
 
# print dictionary
print(emptyDict)
 
# print length of dictionary
print("Length:", len(emptyDict))
 
# print type
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
Previous
Next
Share your thoughts in the comments
Similar Reads