Want to convert the given list:
list = ['A','B','C']
To a dictionary output look like this: Where values of key based 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)}
print(res)
Output:
Another Example
Use built-in functions dict and zip functions.
lst = ['A', 'B', 'C']
res = dict(zip(lst, range(len(lst))))
print(res)
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.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.