Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python array_flip analogue or best way to do this?

Tags:

python

sorting

Is there array_flip (php) analogue for Python 3.x?

from

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

to

{'a': 1, 'c':2, 'b': 3}
like image 928
SlowSuperman Avatar asked Feb 25 '26 16:02

SlowSuperman


1 Answers

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}
like image 168
brianpck Avatar answered Feb 28 '26 04:02

brianpck