Python: Convert list to dictionary with indexes as values

You can get the indices of a list from the built-in enumerate. You just need to reverse the index value map and use a dictionary comprehension to create a dictionary

>>> lst = ['A','B','C']
>>> {k: v for v, k in enumerate(lst)}
{'A': 0, 'C': 2, 'B': 1}

Ohh, and never name a variable to a built-in or a type.


Use built-in functions dict and zip :

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

Python dict constructor has an ability to convert list of tuple to dict, with key as first element of tuple and value as second element of tuple. To achieve this you can use builtin function enumerate which yield tuple of (index, value).

However question's requirement is exact opposite i.e. tuple should be (value, index). So this requires and additional step to reverse the tuple elements before passing to dict constructor. For this step we can use builtin reversed and apply it to each element of list using map

>>> lst = ['A', 'B', 'C']
>>> dict(map(reversed, enumerate(lst)))
>>> {'A': 0, 'C': 2, 'B': 1}