0

Being new to Python, I am studying the following codes:

a_0 = {"what": "b"}
a_1 = {"what": "c"}
a_2 = {"what": "d"}

items = [] # empty list

for i_no in range(10): # fill the list with 10 identical a_0 dicts
    i_new = dict(a_0)
    items.append(i_new)

for i in items[0:5]: # change the first 5 items
    if i["what"] == "b": # try to change the 'i' to be a_1 dicts
        i = dict(a_1)
        # print(i) shows changes

for i in items: 
    print(i)
    # print(i) does not show changes

If the above change works then first 5 items should be the same as a_1, while the last 5 unchanged. But the printed outcome did not match my expectation and this confused me. I want to know whether I missed something. Are there any more convenient ways to change each dictionary in the list? Many thanks.

BartoszKP
  • 34,786
  • 15
  • 102
  • 130
Yuki.F
  • 141
  • 5

2 Answers2

0
for i in items[0:5]: # change the first 5 items
    if i["what"] == "b": # try to change the 'i' to be a_1 dicts
        i = dict(a_1)
        # print(i) shows changes

When you create the loop ... i is a local variable which contains the dictionary from positions [0:5]

When you do:

i = dict(a_1)

You are changing the local variable but not the value in the list. Iterate over the indices and change directly in the list

for i in range(0, 5): # change the first 5 items
    if items[i]["what"] == "b": # try to change the 'i' to be a_1 dicts
        items[i] = dict(a_1)
        # print(items[i]) shows changes

Now you have changed the items in the list and not the value of a local variable

mementum
  • 3,153
  • 13
  • 20
0

That is because you are trying to change 'i' which just holds the value of each item in the 'items' list. Try this:

a_0 = {"what": "b"}
a_1 = {"what": "c"}
a_2 = {"what": "d"}

items = []

for i_no in range(10):
    i_new = dict(a_0)
    items.append(i_new)

for index,i in enumerate(items[0:5]):
    if i["what"] == "b": 
        items[index] = dict(a_1)

for i in items: 
    print i
magenta
  • 53
  • 5