This tutorial will discuss about unique ways to initialize empty dictionary in Python?.
Table Of Contents
An empty dictionary means that there are no key-value pairs in the dictionary. There are 2 ways to create an empty dictionary in Python lets discuss them one by one.
Initialize an empty dictionary using curly braces
To create an empty dictionary we can just provide the open and closed curly braces i.e. {}. It will return an empty dictionary object. Like this,
dictObj = {}
Here we have created an empty dictionary object. Now if we check the size of this object it will be zero, which means there will be 0 key-value pairs in this dictionary.
Let’s see the complete example,
# Create an empty dictionary dictObj = {} print(dictObj) print('Number of Keys in Dictionary are : ', len(dictObj))
Output
Frequently Asked:
- Python: Dictionary with multiple values per key
- How to Add new keys to a Dictionary in Python?
- Can a dictionary have duplicate keys in Python?
- How to get first key in Dictionary – Python
{} Number of Keys in Dictionary are : 0
Initialize an empty dictionary using dict() constructor
The dictionary class in Python provides a constructor, and if we don’t provide any arguments in this constructor, then it will return an empty dictionary object. Like this,
dictObj = dict()
Here we have created an empty dictionary object. Now if we check the size of this object it will be zero, which means there will be 0 key-value pairs in this dictionary.
Let’s see the complete example,
# Create an empty dictionary dictObj = dict() print(dictObj) print('Number of Keys in Dictionary are : ', len(dictObj))
Output
{} Number of Keys in Dictionary are : 0
Add key-value pairs in the empty Dictionary
If you have created an empty dictionary then most probably you are planning to add key value pairs in this empty dictionary at a later stage. You can do that using the subscript operator like this,
dictObj['Ritika'] = 38 dictObj['Smriti'] = 30 dictObj['Atharv'] = 21
Here we added 3 key value pairs in the empty dictionary.
Let’s see the complete example,
# Create an empty dictionary dictObj = dict() # Add new key value pairs in empty dictionary dictObj['Ritika'] = 38 dictObj['Smriti'] = 30 dictObj['Atharv'] = 21 print(dictObj) print('Number of Keys in Dictionary are : ', len(dictObj))
Output
{'Ritika': 38, 'Smriti': 30, 'Atharv': 21} Number of Keys in Dictionary are : 3
Summary
We learned about two different ways to initialize an empty dictionary in Python.