Updating values in a dictionary

Chris Rebert clp2 at rebertia.com
Sun May 16 13:48:24 EDT 2010


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