Updating values in a dictionary
Peter Otten
__peter__ at web.de
Sun May 16 13:58:13 EDT 2010
Chris Rebert wrote:
> 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)])
Another way to skin the cat:
>>> row = dict.fromkeys(range(3), 0)
>>> matrix = dict((x, row.copy()) for x in range(-3, 4))
>>> matrix[2][1] += 1
>>> matrix[-1][2] += 1
>>> from pprint import pprint
>>> pprint(matrix)
{-3: {0: 0, 1: 0, 2: 0},
-2: {0: 0, 1: 0, 2: 0},
-1: {0: 0, 1: 0, 2: 1},
0: {0: 0, 1: 0, 2: 0},
1: {0: 0, 1: 0, 2: 0},
2: {0: 0, 1: 1, 2: 0},
3: {0: 0, 1: 0, 2: 0}}
More information about the Python-list
mailing list