Updating values in a dictionary

Thomas thom.1948 at live.com
Sun May 16 14:39:38 EDT 2010


Chris

Wow, that was a very fast response.
Thank you, it works  (of course)...

Cheers

"Chris Rebert" <clp2 at rebertia.com> wrote in message 
news:mailman.264.1274032106.32709.python-list at python.org...
> On Sun, May 16, 2010 at 10:36 AM, Thomas <thom1948 at gmail.com> wrote:
>> Greetings
>>
>> I am having a darn awful time trying to update a matrix:
>>
>> row = dict([(x,0) for x in range(3)])
>> matrix = dict([(x,row) for x in range(-3,4,1)])
>
> All the columns refer to the very same row dict (`row` obviously).
> Python doesn't do any copying unless you explicitly request it.
>
> Try:
> matrix = dict([(x, dict([(x,0) for x in range(3)]) ) for x in 
> range(-3,4,1)])
>
> This way, the row-creation code gets called for each column and thus
> fresh row dicts are created rather than all just referencing the exact
> same one row dict.
> Nested comprehensions may be hard to understand, so you may wish to
> write it using a function instead:
>
> def make_row():
>    return dict([(x,0) for x in range(3)])
>
> matrix = dict([(x,make_row()) for x in range(-3,4,1)])
>
> See also 
> http://www.python.org/doc/faq/programming/#how-do-i-create-a-multidimensional-list
>
> Cheers,
> Chris
> --
> http://blog.rebertia.com 




More information about the Python-list mailing list