1

When I update a value of my dictionary in the loop, it also changes the values of the dictionary already in the list.

I've already tried the following code in Python 3.7

d = {"name": "v0"}
a = []
b = ["v1", "v2", "v3"]
for i in b:
    d["name"] = i
    a.append(d)
print(a)

I expect that it changes the dictionary in the loop, and adds each representation to the list. However, it adds the same value to the list.

lorenzkort
  • 73
  • 1
  • 10
  • 1
    Never try to modify a dictionary by iterating over it and modifying it in-place. Either [use a dict comprehension over `dict.items()`](https://stackoverflow.com/a/22214248/202229), or take a copy of the dict. – smci May 20 '19 at 08:42
  • What the expected output here? – Devesh Kumar Singh May 20 '19 at 08:48
  • Your code is overriding the key values each time as you are using single key as hard coded. Dictionary did not allow you to store same key more than one time. – Pradeep Pandey May 20 '19 at 09:07
  • If you make key dynamic and distinct it allows you to store it: b = ["v1", "v2", "v3"] d = {"name": "v0"} for i in range(len(b)): d["name-"+str(i)]=b[i] print(d) otherwise append directly without assigning to dict each key -value pair element: a=[{"name": "v0"}] b = ["v1", "v2", "v3"] for i in range(len(b)): a.append({"name":b[i]}) print(a) – Pradeep Pandey May 20 '19 at 09:23

1 Answers1

5

Create a new dictionary each time:

a = []
b = ["v1", "v2", "v3"]
for i in b:
    a.append({"name": i})
print(a)

As a comprehension:

a = [{"name": i} for i in b]

If your dictionary is too big, you can rebuild another one from it with a comprehension:

a = [{"name": i if k == "name" else k:v for k,v in d.items() for i in b]
Netwave
  • 40,134
  • 6
  • 50
  • 93