
04-30-2009, 06:09 PM
|
|
|
Re: using zip() and dictionaries
> On Apr 30, 12:45Â*pm, Sneaky Wombat <> wrote:
>> 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.
On Thu, Apr 30, 2009 at 11:00 AM, Sneaky Wombat <joe.hrbek@gmail.com> wrote:
> quick update,
>
> #change this line:
> for (k,v) in zip(header,[[]]*len(header)):
> #to this line:
> for (k,v) in zip(header,[[],[],[],[]]):
>
> and it works as expected. Something about the [[]]*len(header) is
> causing the weird behavior. I'm probably using it wrong, but if
> anyone can explain why that would happen, i'd appreciate it. My guess
> is that it's iterating through the the whole dictionary because of the
> value on the right in zip().
Read http://www.python.org/doc/faq/progra...mensional-list
Basically, the multiplication doesn't create new sub-lists, it just
copies references to the one original empty sublist.
Cheers,
Chris
--
http://blog.rebertia.com
|