How to Create a Dictionary in Python

Here are 2 ways to create a Dictionary in Python:

(1) Using curly brackets {}

my_dictionary = {1: 'aaa', 2: 'bbb', 3: 'ccc'}

(2) Using the dict() function

my_dictionary = dict({1: 'aaa', 2: 'bbb', 3: 'ccc'})

Note that each dictionary stores data in key:value pairs. In addition, the keys must be unique and cannot be repeated.

Examples of dictionaries

Example 1: create a dictionary in Python using curly brackets {}

Let’s create a simple dictionary using the curly brackets {} approach:

my_dictionary = {1: 'blue', 2: 'green', 3: 'red', 4: 'yellow', 5: 'orange'}
print(my_dictionary)
print(type(my_dictionary))

As you can see, we got the following dictionary. Note that the syntax of print(type(my_dictionary)) was added at the bottom of the code to demonstrate that we created a dictionary:

{1: 'blue', 2: 'green', 3: 'red', 4: 'yellow', 5: 'orange'}
<class 'dict'>

Example 2: create a dictionary using the dict() function

Optionally, you may use the dict() function to create a dictionary:

my_dictionary = dict({1: 'blue', 2: 'green', 3: 'red', 4: 'yellow', 5: 'orange'})
print(my_dictionary)
print(type(my_dictionary))

You’ll get the same results:

{1: 'blue', 2: 'green', 3: 'red', 4: 'yellow', 5: 'orange'}
<class 'dict'>

Example 3: create a dictionary with lists

Finally, let’s create a dictionary, where each value in the dictionary would be a list:

my_dictionary = {1: ['blue', 'navy blue', 'royal blue'],
                 2: ['green', 'forest green', 'dark green'],
                 3: ['red', 'dark red', 'maroon']
                 }
print(my_dictionary)
print(type(my_dictionary))

Result:

{1: ['blue', 'navy blue', 'royal blue'], 2: ['green', 'forest green', 'dark green'], 3: ['red', 'dark red', 'maroon']}
<class 'dict'>