pythonic way to associate list elements with their indices

Posted by Dragan Chupacabrovic on Stack Overflow See other posts from Stack Overflow or by Dragan Chupacabrovic
Published on 2010-05-14T03:28:02Z Indexed on 2010/05/14 3:34 UTC
Read the original article Hit count: 356

Filed under:
|
|
|
|

Hello Everybody,

I have a list of values and I want to put them in a dictionary that would map each value to it's index.

I can do it this way:

>>> t = (5,6,7)
>>> d = dict(zip(t, range(len(t))))
>>> d
{5: 0, 6: 1, 7: 2}

this is not bad, but I'm looking for something more elegant.

I've come across the following, but it does the opposite of what I need:

>>> d = dict(enumerate(t))
>>> d
{0: 5, 1: 6, 2: 7}

Please share your solutions,
Thank you

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary