Skip to main content

How to convert a list to a dictionary in Python

How to convert a list to a dictionary in Python.

Here's a step-by-step tutorial on how to convert a list to a dictionary in Python:

1: Create a list

Start by creating a list that you want to convert to a dictionary. For example, let's create a list of fruits:

fruits = ['apple', 'banana', 'orange']

2: Initialize an empty dictionary

Next, initialize an empty dictionary that will hold the converted values from the list:

fruit_dict = {}

3: Loop through the list

Now, loop through each element in the list using a for loop:

for fruit in fruits:

4: Add elements to the dictionary

Inside the loop, add each element from the list as a key in the dictionary, and assign a value to it. You can choose any value you want. Let's assign a value of 0 to each fruit for this example:

    fruit_dict[fruit] = 0

5: Complete the loop

After adding the element to the dictionary, the loop will move to the next element in the list and repeat the process.

6: Print the dictionary

Finally, print the converted dictionary to see the result:

print(fruit_dict)

The complete code would look like this:

fruits = ['apple', 'banana', 'orange']
fruit_dict = {}

for fruit in fruits:
fruit_dict[fruit] = 0

print(fruit_dict)

Output:

{'apple': 0, 'banana': 0, 'orange': 0}

That's it! You have successfully converted a list to a dictionary in Python.