Skip to content

Python initialize the empty dictionary | Basics

  • by

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 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 an 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 or suggestions on this Python dictionary topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading