Updating values in a dictionary

superpollo utente at esempio.net
Sun May 16 13:51:41 EDT 2010


Thomas ha scritto:
> 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)])
> 
> matrix[2][1] += 1
> matrix[-1][2] += 1
> 
> """
> Got: a 1 in all col 1 and 2
> {-3: {0: 0, 1: 1, 2: 1},
>  -2: {0: 0, 1: 1, 2: 1},
>  -1: {0: 0, 1: 1, 2: 1},
>   0: {0: 0, 1: 1, 2: 1},
>   1: {0: 0, 1: 1, 2: 1},
>   2: {0: 0, 1: 1, 2: 1},
>   3: {0: 0, 1: 1, 2: 1}}
> Expected: a 1 in row 2 col 1 and row -1 col 2
> {-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}}
> """
> 
> I must be doing something wrong. Researched and researched. Nothing
> clicks.

clone the row:

 >>> row = dict([(x,0) for x in range(3)])
 >>> import copy
 >>> matrix = dict([(x,copy.copy(row)) for x in range(-3,4,1)])
 >>> matrix[2][1] += 1
 >>> matrix[-1][2] += 1
 >>> import pprint
 >>> pp = pprint.PrettyPrinter()
 >>> pp.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}}
 >>>

bye




More information about the Python-list mailing list