Odd nested dictionary behavior in python
- by adept
Im new two python and am trying to grow a dictionary of dictionaries. I have done this in php and perl but python is behaving very differently. Im sure it makes sense to those more familiar with python. Here is my code:
colnames = ['name','dob','id'];
tablehashcopy = {};
tablehashcopy = dict.fromkeys(colnames,{});
tablehashcopy['name']['hi'] = 0;
print(tablehashcopy);
Output:
{'dob': {'hi': 0}, 'name': {'hi': 0}, 'id': {'hi': 0}}
The problem arises from the 2nd to last statement(i put the print in for convenience). I expected to find that one element has been added to the 'name' dictionary with the key 'hi' and the value 0. But this key,value pair has been added to EVERY sub-dictionary. Why?
I have tested this on my ubuntu machine in both python 2.6 and python 3.1 the behaviour is the same.