I am trying to convert the following list:
list = [\'A\',\'B\',\'C\']
To a dictionary like:
dict = {\'A\':0, \'B\':1, \'C\'
You have to convert the unhashable list into a tuple:
dct = {tuple(key): idx for idx, key in enumerate(lst)}
Use built-in functions dict and zip :
>>> lst = ['A','B','C']
>>> dict(zip(lst,range(len(lst))))
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.
Don't use list
as your variable name because it's reserved by Python. You can also take advantage of enumerate
.
your_list = ['A', 'B', 'C']
dict = {key: i for i, key in enumerate(your_list)}
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}