Python - Convert List to Index and Value dictionary

Python - Convert List to Index and Value dictionary

If you want to convert a list into a dictionary where keys are the indices and values are the elements from the list, you can accomplish this with dictionary comprehension.

Given:

A list:

lst = ["apple", "banana", "cherry"] 

Desired Outcome:

A dictionary:

{ 0: "apple", 1: "banana", 2: "cherry" } 

Tutorial:

1. Use enumerate() Function:

The enumerate() function returns both the index and the value of each item in the list.

2. Apply Dictionary Comprehension:

Use dictionary comprehension to generate the desired dictionary structure.

dict_result = {index: value for index, value in enumerate(lst)} 

3. Print the Result:

print(dict_result) 

Full Code:

lst = ["apple", "banana", "cherry"] dict_result = {index: value for index, value in enumerate(lst)} print(dict_result) 

Output:

{ 0: "apple", 1: "banana", 2: "cherry" } 

Notes:

  • The enumerate() function is an efficient way to iterate over both the indices and the items of a list.

  • By default, enumerate() starts indexing from 0. If you want to start indexing from a different number, you can provide a start argument. For instance, enumerate(lst, start=1) would start indexing from 1.


More Tags

color-detection clipboard typescript2.0 memoization sharepoint-online gis monitor autofac rest-client fillna

More Programming Guides

Other Guides

More Programming Examples