Is there array_flip (php) analogue for Python 3.x?
from
obj = ['a', 'c', 'b' ]
to
{'a': 1, 'c':2, 'b': 3}
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}
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