Python convert list to Dictionary with index as key | Example code

Want to convert the given list:

list = ['A','B','C']

To a dictionary output look like: Where values of key bases on the current index value of the element in the list.

dict = {'A':0, 'B':1, 'C':2}

Example convert list to a dictionary with index as a key in Python

Simple example code.

First, get the indices of a list from using enumerate function. And just need to reverse the index value map and use a dictionary comprehension to create a dictionary

lst = ['A','B','C']
res = {k: v for v, k in enumerate(lst)}



Python convert list to Dictionary with index as key

Another Example

Use built-in functions dict and zip functions.

lst = ['A', 'B', 'C']
res = dict(zip(lst, range(len(lst))))


Output: {‘A’: 0, ‘B’: 1, ‘C’: 2}

Do comment if you have any doubts and suggestions on this Python dictionary list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.