How to make a python dictionary from the list

"Learn how to turn a Python list into a dictionary with an easy example!"

Creating a Python Dictionary from a List

Python provides several ways to create a dictionary from a list. Here is an example of how to create a dictionary from a list of two-element tuples:
# Create a list of two-element tuples
lst = [("A", 1), ("B", 2), ("C", 3)]

# Create a dictionary from the list
my_dict = dict(lst)

# Print the dictionary
print(my_dict)
The output of the print() statement will look like this:
{'A': 1, 'B': 2, 'C': 3}
If you have a list of two-element lists, you can use the same technique to create a dictionary:
# Create a list of two-element lists
lst = [['A', 1], ['B', 2], ['C', 3]]

# Create a dictionary from the list
my_dict = dict(lst)

# Print the dictionary
print(my_dict)
The output of the print() statement will be the same:
{'A': 1, 'B': 2, 'C': 3}
You can also create a dictionary from a list of key-value pairs. Here is an example of how to do this:
# Create a list of key-value pairs
lst = [("A", 1), ("B", 2), ("C", 3)]

# Create a dictionary from the list
my_dict = dict(lst)

# Print the dictionary
print(my_dict)
Again, the output of the print() statement will be the same:
{'A': 1, 'B': 2, 'C': 3}
Finally, you can also create a dictionary from two separate lists. Here is an example of how to do this:
# Create two separate lists
keys = ["A", "B", "C"]
values = [1, 2, 3]

# Create a dictionary from the lists
my_dict = dict(zip(keys, values))

# Print the dictionary
print(my_dict)
The output of the print() statement will be the same:
{'A': 1, 'B': 2, 'C': 3}
As you can see, Python provides several ways to create a dictionary from a list. You can choose the one that best suits your needs.

Answers (0)