This post will discuss how to create and initialize a dictionary in Python.

A dictionary consists of key-value pairs. There are several ways to create and initialize a dictionary in Python, as discussed below:

1. Using Dictionary Constructor

The dictionary constructor dict() returns a new dictionary that is initialized from the specified arguments.

 
If a mapping object is passed to the dictionary constructor, the dictionary is created with the same key-value pairs as the mapping object.

Download  Run Code

 
You can also pass an iterable to the dictionary constructor, where each item in the iterable must be another iterable with two objects.

This returns a new dictionary with the first object of each item as key and the second object as its corresponding value. Note that if a key is repeated, the resultant dictionary contains the last value for that key.

Download  Run Code

 
If no argument is passed to the dictionary constructor, an empty dictionary is created.

Download  Run Code

2. Using Dictionary Literal Syntax

Dictionaries can also be created by placing a comma-separated list of key: value pairs within braces.

Download  Run Code

 
If no key-value pair is passed, an empty dictionary is created.

Download  Run Code

3. Using fromkeys() function

If you want to initialize all keys in the dictionary with some default value, you can use the fromkeys() function.

Download  Run Code

 
If no default value is specified, the dictionary is initialized with all values as None.

Download  Run Code

 
Note that if the default value is mutable, it might lead to unexpected results. For example, in the following program, all keys get mapped to the same list. This means that any changes made to any value will be reflected in all dictionary’s values.

Download  Run Code

 
Read about – defaultdict, OrderedDict

That’s all about creating and initializing a Python dictionary.