Home > Software design >  Append different value to same name key in list of dictionaries [duplicate]
Append different value to same name key in list of dictionaries [duplicate]

Time:09-21

I want an output like this:

 [{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]

But I am getting this output:

  [{'a': 3}, {'a': 3}, {'a': 3}, {'a': 3}]

I tried the below code:

  l = []
  d = {}
  for i in range(0,4):
     d['a'] = i
     print("dictinary ",d)
     print("list before appending ",l)
     l.append(d)
     print("list after appending ",l)
  print(l)

I am getting the below output after applying print statements(for debugging)

    dictinary  {'a': 0}
    list before appending  []
    list after appending  [{'a': 0}]
    dictinary  {'a': 1}
    list before appending  [{'a': 1}]
    list after appending  [{'a': 1}, {'a': 1}]
    dictinary  {'a': 2}
    list before appending  [{'a': 2}, {'a': 2}]
    list after appending  [{'a': 2}, {'a': 2}, {'a': 2}]
    dictinary  {'a': 3}
    list before appending  [{'a': 3}, {'a': 3}, {'a': 3}]
    list after appending  [{'a': 3}, {'a': 3}, {'a': 3}, {'a': 3}]
    [{'a': 3}, {'a': 3}, {'a': 3}, {'a': 3}]

I cannot understand one thing: Why my list value is getting changed on changing dictionary value ? i.e. On executing line no 4 in code, the value of the list is automatically getting changed(See line no 5 of output). Please suggest something.

CodePudding user response:

create new dictionary In for-loop. in Your code you have one dictionary with one address when changing one of them all changing. Try this:

l = []
for i in range(0,4):
    d = {}
    d['a'] = i
    print("dictinary ",d)
    print("list before appending ",l)
    l.append(d)
    print("list after appending ",l)
print(l)

Output:

dictinary  {'a': 0}
list before appending  []
list after appending  [{'a': 0}]
dictinary  {'a': 1}
list before appending  [{'a': 0}]
list after appending  [{'a': 0}, {'a': 1}]
dictinary  {'a': 2}
list before appending  [{'a': 0}, {'a': 1}]
list after appending  [{'a': 0}, {'a': 1}, {'a': 2}]
dictinary  {'a': 3}
list before appending  [{'a': 0}, {'a': 1}, {'a': 2}]
list after appending  [{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]
[{'a': 0}, {'a': 1}, {'a': 2}, {'a': 3}]
  • Related