-3

I have a nested list x. The inner list have dictionaries as the element.

y = [{'hello1': 1, 'hello2': 2, 'hello3': 3}, {'hello1': 1, 'hello2': 2, 'hello3': 3}]
x = []
for i in range(0,3):
    x.append(y)

counter = 5
for i in x:
    for j in i :
        j['hello2'] = counter
    counter = counter + 1

print(x)

The output that i got

[
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ]
]

The output that I am looking for

[
  [
    {
      'hello1': 1,
      'hello2': 5,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 5,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 6,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 6,
      'hello3': 3
    }
  ],
  [
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    },
    {
      'hello1': 1,
      'hello2': 7,
      'hello3': 3
    }
  ]
]

I wanted the first list to have hello2 value as 5, the second list's hello2 value as 6 and the third list's hello2 value as 7. Please provide me with valid inputs on what modifications are required. Thank You

Stan11
  • 274
  • 3
  • 11

1 Answers1

3

Dict is mutable, so at every iteration you are adding the same dict, so every time you update the same dict.

You need to make a copy:

x.append(deepcopy(y)) 
oreopot
  • 3,392
  • 2
  • 19
  • 28
Al Wld
  • 869
  • 7
  • 19