How to convert a list to a dictionary with indexes as values?

Question:

I am trying to convert the following list:

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

To a dictionary like:

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

I have tried answers from other posts but none is working for me. I have the following code for now:

d = {l[i]: i for i in range(len(l))}

Which gives me this error:

unhashable type: 'list'
Asked By: ahajib

||

Answers:

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}
Answered By: Abhijit

You can also take advantage of enumerate:

your_list = ['A', 'B', 'C']
your_dict = {key: i for i, key in enumerate(your_list)}
Answered By: gr1zzly be4r

You have to convert the unhashable list into a tuple:

dct = {tuple(key): idx for idx, key in enumerate(lst)}
Answered By: Daniel

Use built-in functions dict and zip:

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

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}
Answered By: Sohaib Farooqi

The easiest solution I used was:

lst = list('ABC')
dict(enumerate(lst))

edit: This is the reverse of what the author needed and exactly what I needed

Answered By: Christo Joseph
  1. If the elements in target list are unique, then a dict comprehension should be enough and elegant, just like the accepted answer.

    >>> lst = ['A', 'B', 'C']
    >>> pos_map = {ele: pos for pos, ele in enumerate(lst)}
    
  2. But if there were duplicated elements in target list, then we could use the handy defaultdict in collections module:

    >>> lst = ['A', 'B', 'C', 'A', 'A', 'B']
    >>> from collections import defaultdict
    >>> pos_map = defaultdict(list)
    >>> for pos, ele in enumerate(lst):
    >>>     pos_map[ele].append(pos)
    >>>
    >>> pos_map
    >>> defaultdict(list, {'A': [0, 3, 4], 'B': [1, 5], 'C': [2]})
    
Answered By: YaOzI
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.