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.
The issue is with your fromkeys call. You passed it an empty dictionary, and it used that exact same empty dictionary as the value for all of the keys. Since the exact same dictionary is being used as the value, adding an element to it means you’ll see that same element for all the keys’ dictionaries.