Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python dictionary update method

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!

like image 864
freshWoWer Avatar asked Oct 06 '08 05:10

freshWoWer


People also ask

What is the use of update method in dictionary in Python?

Python Dictionary update() Method The update() method inserts the specified items to the dictionary. The specified items can be a dictionary, or an iterable object with key value pairs.

What does Python 3's dictionary update () method do dict1 update dict2?

Python 3 - dictionary update() Method The method update() adds dictionary dict2's key-values pairs in to dict. This function does not return anything.

How do I update a dictionary value?

In order to update the value of an associated key, Python Dict has in-built method — dict. update() method to update a Python Dictionary. The dict. update() method is used to update a value associated with a key in the input dictionary.

Can we update the key in dictionary python?

Python update() method updates the dictionary with the key and value pairs. It inserts key/value if it is not present. It updates key/value if it is already present in the dictionary.


1 Answers

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.

like image 108
Jerub Avatar answered Oct 10 '22 08:10

Jerub