SlowSuperman
SlowSuperman

Reputation: 628

Python array_flip analogue or best way to do this?

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

Answers (1)

brianpck
brianpck

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

Related Questions