Programming

How to convert a list into a dictionary in Python

To convert a list to a dictionary in Python, you can use the built-in dict() function or a dictionary comprehension. Here are two ways to do it:

Method 1: Using the dict() function

# List of tuples (key-value pairs)
my_list = [('a', 1), ('b', 2), ('c', 3)]

# Convert list to dictionary
my_dict = dict(my_list)

# Print the dictionary
print(my_dict)

Output:

{'a': 1, 'b': 2, 'c': 3}

Method 2: Using a dictionary comprehension

# List of dictionaries
my_list = [{'a': 1}, {'b': 2}, {'c': 3}]

# Convert list to dictionary
my_dict = {k: v for d in my_list for k, v in d.items()}

# Print the dictionary
print(my_dict)

Output:

{'a': 1, 'b': 2, 'c': 3}

Read More: Best 10 Minute School Courses

In both methods, we first define a list and then convert it to a dictionary using either the dict() function or a dictionary comprehension. The resulting dictionary contains the same data as the original list, with each list item being represented as a key-value pair in the dictionary.

What is your reaction?

0
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly

Leave a reply

Your email address will not be published. Required fields are marked *