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 {}

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))

The resulted dictionary:

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

Note that “print(type(my_dictionary))” was added at the bottom of the code to demonstrate that you created a dictionary:

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

Optionally, 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, 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))

The result:

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

Leave a Comment