using zip() and dictionaries

Arnaud Delobelle arnodel at googlemail.com
Thu Apr 30 20:48:09 CEST 2009


Sneaky Wombat <joe.hrbek at gmail.com> writes:

> I'm really confused by what is happening here.  If I use zip(), I
> can't update individual dictionary elements like I usually do.  It
> updates all of the dictionary elements.  It's hard to explain, so here
> is some output from an interactive session:
>
> In [52]: header=['a','b','c','d']
> In [53]: columnMap={}
> In [54]: for (k,v) in zip(header,[[]]*len(header)):
>    ....:     #print "%s,%s"%(k,v)
>    ....:     columnMap[k] = v
>    ....:
> In [55]: columnMap
> Out[55]: {'a': [], 'b': [], 'c': [], 'd': []}
> In [56]: columnMap['a'].append('something')
> In [57]: columnMap
> Out[57]:
> {'a': ['something'],
>  'b': ['something'],
>  'c': ['something'],
>  'd': ['something']}
>
> Why does ['something'] get attached to all columnMap elements instead
> of just element 'a'?
>
>
> In [58]: columnMap={'a': [], 'b': [], 'c': [], 'd': []}
> In [59]: columnMap['a'].append('something')
> In [60]: columnMap
> Out[60]: {'a': ['something'], 'b': [], 'c': [], 'd': []}
>
> creating the dictionary without using zip, it works as normal.

It's a FAQ:

http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list

-- 
Arnaud



More information about the Python-list mailing list