Odd nested dictionary behavior in python

Posted by adept on Stack Overflow See other posts from Stack Overflow or by adept
Published on 2010-03-12T15:39:18Z Indexed on 2010/03/12 15:57 UTC
Read the original article Hit count: 325

Filed under:
|
|
|

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.

© Stack Overflow or respective owner

Related posts about python

Related posts about dictionary