简体   繁体   中英

Inserting variables into a dictionary in Python

Why is this code adding the key but not the value for a dictionary in Python?

Here is the result:

$ python hashtest.py
set(['yes:no'])
set(['hi', 'yes:no'])

And the code is as follows:

hashmap={"yes:no"}

print hashmap
var1="hi"
var2="bye"

#hashmap[var1]=var2
#print hashmap

hashmap.update({var1:var2})
print hashmap

The first method ( hashmap[var1] = var2 ) gave a type error (assignment).

TIA

I would suggest you to understand first what kind of data structure would you need for your purpose.

This question might be useful. In particular,

• Use a dictionary when you have a set of unique keys that map to values.

• Use a set to store an unordered set of items.

You can find an extensive explanation in chapter 4 of High Performance Python

In your case, it seems you want to create a dictionary , so this should help you out

>>> hashmap = {}
>>> hashmap["yes"] = "no"
>>> hashmap
{'yes': 'no'}
>>> var1="hi"
>>> var2="bye"
>>> hashmap[var1] = var2
>>> hashmap
{'yes': 'no', 'hi': 'bye'}

It looks like you're trying to change the value of a given key in a dictionary. Here's some code that will do that.

>>> mydict = {'hi' : 'hello', 'bye' : 'goodbye', 'see ya' : None }
>>> print mydict
{'bye': 'goodbye', 'hi': 'hello', 'see ya': None}
>>> mydict['see ya'] = mydict['bye']
>>> mydict
{'bye': 'goodbye', 'hi': 'hello', 'see ya': 'goodbye'}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM