Python dictionary created and initialized by using curly brackets {}, and it contains keys and value pairs. Another way is to use dict() Constructor to Initialize a Python Dictionary.
Python initialize dictionary example
Simple basic example code Initialize dict using {}(blank curly braces).
dict1 = {'X': 2, 'Y': 3, 'Z': 4}
print(dict1)
print(type(dict1))
Output:
Using dict() Constructor
Simple pass parameters in the dict() constructor and create a dictionary.
dict1 = dict(X=1, Y=2, Z=3)
print(dict1)
Output: {‘X’: 1, ‘Y’: 2, ‘Z’: 3}
Initialize dict with the same values
The fromkeys() function can be used if all the keys have the same value.
dict1 = dict.fromkeys(['A', 'B', 'C'], 0)
print(dict1)
Output: {‘A’: 0, ‘B’: 0, ‘C’: 0}
How to Initialize Dictionary with None values?
Answer: use dict.fromkeys() function to initialize the dictionary with None values.
dict1 = dict.fromkeys(['A', 'B', 'C'])
print(dict1)
Output: {‘A’: None, ‘B’: None, ‘C’: None}
Do comment if you have any doubts or suggestions on this Python basic 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.