0

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

linusg
  • 6,289
  • 4
  • 28
  • 78
Tom Franks
  • 41
  • 1
  • 1
  • 3
  • 2
    `hashmap={"yes:no"}` creates a `set`, not a `dict`. FWIW, a `set` is essentially a `dict` with keys but no values. – PM 2Ring Apr 18 '16 at 15:10
  • 2
    You should use `hashmap = {"yes":"no"}` to create a dictionary, here you're creating a set. – Aurel Apr 18 '16 at 15:11

2 Answers2

4

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'}
Community
  • 1
  • 1
mabe02
  • 2,676
  • 2
  • 20
  • 35
0

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'}
rajah9
  • 11,645
  • 5
  • 44
  • 57
  • Here's a popular SO link for adding a value to a dictionary: http://stackoverflow.com/questions/1024847/add-key-to-a-dictionary-in-python – rajah9 Apr 18 '16 at 16:09