Python initialize the empty dictionary | Basics

Don’t use any values or elements inside the {} curly bracket to initialize the empty dictionary in Python. The empty dictionary can also create by dict() built-in function without any arguments

dictionary = {}

OR

dict = dict()

Example initialize an empty dictionary in Python

Simple example code with both ways.

dict1 = {}
print(type(dict1))
print(dict1)

# OR
dict2 = dict()
print(type(dict2))
print(dict2)

Output:

Python initialize the empty dictionary

How to initialize empty dictionary with default values type in Python?

Answer: Use the defaultdict function to initiate an empty dictionary with default values.

from collections import defaultdict

mydict = defaultdict(set)
mydict["key"].add(5)

print(mydict)

Output: defaultdict(, {‘key’: {5}})

Do comment if you have any doubts and suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.