views:

2647

answers:

6

I have a list string tag.

I am trying to initialize a dictionary with the key as the tag string and values as the array index.

for i, ithTag in enumerate(tag):
    tagDict.update(ithTag=i)

The above returns me {'ithTag': 608} 608 is the 608th index

My problem is that while the i is being interpreted as a variable, Python is treating the "ithTag" as a string instead of a variable.

I'm confused, it is kind of hard to google these kind of specific questions. I hope I worded the title of this question correctly,

Thanks!

+11  A: 

You actually want to do this:

for i, tag in enumerate(tag):
    tagDict[tag] = i

The .update() method is used for updating a dictionary using another dictionary, not for changing a single key/value pair.

Jerub
+2  A: 

I think this is what you want to do:

d = {}
for i, tag in enumerate(ithTag):
   d[tag] = i
Mingus Rude
+2  A: 

Try

tagDict[ithTag] = i
Vinko Vrsalovic
A: 

Thanks!

for i, tag in enumerate(tag): tagDict[tag] = i

freshWoWer
+3  A: 

If you want to be clever:

tagDict.update(enumerate(tag))

Thanks to Brian for the update. This is apparently ~5% faster than the iterative version.

Claudiu
Actually, update() can take a sequence directly, so there's no need to construct an intermediate dict. Doing tagDict.update(enumerate(tag)) is actually slightly (~5%) quicker than the iterative version.
Brian
+2  A: 

It's a one-liner:

tagDict = dict((tag, i) for i, tag in enumerate(tag))
Torsten Marek