python dictionary update method

2020-08-09 07:14发布

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!

6条回答
欢心
2楼-- · 2020-08-09 07:42

I think what you want is this:

for i, ithTag in enumerate(tag):
    tagDict.update({ithTag: i})
查看更多
干净又极端
3楼-- · 2020-08-09 07:43

If you want to be clever:

tagDict.update(map(reversed, enumerate(tag)))

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

(EDIT: Thanks saverio for pointing out my answer was incorrect (now fixed). Probably the most efficient/Pythonic way would be Torsten Marek's answer, slightly modified:

tagDict.update((t, i) for (i,t) in enumerate(tag))

)

查看更多
你好瞎i
4楼-- · 2020-08-09 07:48

It's a one-liner:

tagDict = dict((t, i) for i, t in enumerate(tag))
查看更多
冷血范
5楼-- · 2020-08-09 07:55

I think this is what you want to do:

d = {}
for i, tag in enumerate(ithTag):
   d[tag] = i
查看更多
一纸荒年 Trace。
6楼-- · 2020-08-09 07:56

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.

查看更多
冷血范
7楼-- · 2020-08-09 08:03

Try

tagDict[ithTag] = i
查看更多
登录 后发表回答