Reputation: 628
Is there array_flip (php) analogue for Python 3.x?
from
obj = ['a', 'c', 'b' ]
to
{'a': 1, 'c':2, 'b': 3}
Upvotes: 3
Views: 367
Reputation: 8254
You can use a list comprehension along with the dict
constructor, as follows:
>>> obj = [ 'a', 'c', 'b' ]
>>> dict((x, i + 1) for i, x in enumerate(obj))
{'a': 1, 'c': 2, 'b': 3}
As noted in the comments, you can also use a simple dict comprehension:
>>> { x: i + 1 for i, x in enumerate(obj) }
{'a': 1, 'c': 2, 'b': 3}
Upvotes: 1