Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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' 
like image 428
ahajib Avatar asked Apr 06 '16 18:04

ahajib


1 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} 
like image 92
Abhijit Avatar answered Sep 21 '22 15:09

Abhijit