How to Convert a List to a Dictionary in Python Using Indexes?

Estimated read time 1 min read

If you want to convert a list to a dictionary using the indexes of the list elements as keys, you can use the enumerate() function along with dictionary comprehension. Here’s an example:

my_list = ['value1', 'value2', 'value3']

my_dict = {index: value for index, value in enumerate(my_list)}


{0: 'value1', 1: 'value2', 2: 'value3'}

In the example above, we have a list called my_list. We use the enumerate() function to generate pairs of indexes and corresponding values from the list. Then, we iterate over these pairs using dictionary comprehension to create key-value pairs in the dictionary. The index serves as the key, and the corresponding list element serves as the value.

You can replace my_list with your own list variable or modify the code to suit your specific needs.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply