init dict Python | With example code

The init dict Python means to initialize a dictionary. Burly braces { } symbol to initialize dictionary in python.

emptyDict = {}

Or you can use the dict() function

emptyDict = dict()

Example init dict Python

Simple example code.

Empty dict (dictionary)

emptyDict = {}



init dict Python

Another example with element init dict

The following code uses literals to initialize a Python dictionary.

dict1 = {'X': 2, 'Y': 3, 'Z': 4}

Output: {‘X’: 2, ‘Y’: 3, ‘Z’: 4}

What is the preferred syntax for initializing a dict: curly brace literals {} or the dict() function?

Answer: Curly braces. Passing keyword arguments into dict(), though it works beautifully in a lot of scenarios, can only initialize a map if the keys are valid Python identifiers.

This works:

a = {'import': 'trade', 1: 7.8}
a = dict({'import': 'trade', 1: 7.8})

This won’t work:

a = dict(import='trade', 1=7.8)

It will result in the following error:

    a = dict(import='trade', 1=7.8)
SyntaxError: invalid syntax


Do comment if you have any doubts and suggestions on this Python dict 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.