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'
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With