-1

I want to create a dictionary where each value is a dictionary. Here's what I have:

start = 1
for i in range(3):
    updated_payload = payload
    updated_payload["params"]["dsoJsonData"]["ReadMap"]["Some"]["StartIndex"] = start
    x[i] = updated_payload
    start = start + 1

Where payload is also a dictionary with all the needed attributes. I am just changing the StartIndex attribute to whatever the loop is at that time. However, when I run this piece of code all my dictionaries' keys have the same exact values. StartIndex all equal to 3. Why are they all getting the same value and how can I fix it so that it gets its respective iteration number?

user2896120
  • 3,180
  • 4
  • 40
  • 100

2 Answers2

1

This is because you're referencing those dicts rather than copying them. So all of your x[i]'s are pointing the same dict. You should be copying them as the following:

x[i] = updated_payload.copy()
saedx1
  • 984
  • 6
  • 20
1

I think you need to make a copy of the payload dictionary. You are directly assigning the value of payload to updated_payload so it's passed by reference instead of being copied.

updated_payload = payload.copy()
Khwarz
  • 11
  • 2