-4

I have a list:

a = ['a', 'b', 'c']

I want to get the dict:

b = {'a':0, 'b':1, 'c':2}

What is the most pythonic way to get that?

yukashima huksay
  • 5,834
  • 7
  • 45
  • 78

4 Answers4

5

Does the following help you?

b = dict(map(lambda t: (t[1], t[0]), enumerate(a)))

Example:

>>> dict(map(lambda t: (t[1], t[0]), enumerate(['a', 'b', 'c'])))
{'b': 1, 'c': 2, 'a': 0}
tgwtdt
  • 362
  • 2
  • 15
2

The simplest (and imo most pythonic) way of doing this would be:

b = dict(enumerate(a))
L3viathan
  • 26,748
  • 2
  • 58
  • 81
2
a = ['a','b','c']
b = dict(enumerate(a))
print(b)

It will produce:

{0: 'a', 1: 'b', 2: 'c'}
0

use index:

a = ['a', 'b', 'c']
dict_a = {}
for x in a:
    dict_a[a.index(x)] = x
print(dict_a)
keramat
  • 4,328
  • 6
  • 25
  • 38