Convert list to dictionary with indexes as Values in Python

avatar

Borislav Hadzhiev

Last updated: Sep 15, 2022

banner

Photo from Unsplash

Convert list to dictionary with indexes as Values in Python #

To convert a list to a dictionary with indexes as values:

  1. Use the enumerate() function to get an object of index and value tuples.
  2. Use a dict comprehension to iterate over the enumerate object.
  3. Return the items as dictionary keys and the indexes as values.
main.py
my_list = ['bobby', 'hadz', 'com'] # ✅ convert list to dictionary with indexes as values my_dict = {value: index for index, value in enumerate(my_list)} print(my_dict) # 👉️ {'bobby': 0, 'hadz': 1, 'com': 2} # ---------------------------------------------------------- # ✅ convert list to dictionary with indexes as keys my_dict = {index: value for index, value in enumerate(my_list)} print(my_dict) # 👉️ {0: 'bobby', 1: 'hadz', 2: 'com'}

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the corresponding item.

main.py
my_list = ['bobby', 'hadz', 'com'] # 👇️ [(0, 'bobby'), (1, 'hadz'), (2, 'com')] print(list(enumerate(my_list)))

The first element in each tuple is the index and the second is the corresponding item.

We used a dict comprehension to iterate over the enumerate object.

main.py
my_list = ['bobby', 'hadz', 'com'] my_dict = {value: index for index, value in enumerate(my_list)} print(my_dict) # 👉️ {'bobby': 0, 'hadz': 1, 'com': 2}

Dict comprehensions are very similar to list comprehensions.

They perform some operation for every key-value pair in the dictionary or select a subset of key-value pairs that meet a condition.

On each iteration, we return the current item as the key and the index as the value.

If you need to convert the list to a dictionary with indexes as keys, switch the return values.

main.py
my_list = ['bobby', 'hadz', 'com'] my_dict = {index: value for index, value in enumerate(my_list)} print(my_dict) # 👉️ {0: 'bobby', 1: 'hadz', 2: 'com'}
I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.