-2
class one:
    def __init__(self,id,d):
        self.id=id
        self.d=d
    def printfun(self):
        for i in l:
            print(i.id,i.d)

l=[]
d={}
for i in range(2):
    id=int(input())
    d["a"]=int(input())
    d["b"]=int(input())
    o=one(id,d)
    l.append(o)
o.printfun()

and my output is: 100 1 2 101 3 4 100 {'a': 3, 'b': 4} 101 {'a': 3, 'b': 4} I append dictionary to a list, while printing i get only the last appended thing in the dictionary of the list. How to get all the dictionary i have appended in the list, and why i am not getting first dictionary i had appended in the list.

1 Answers1

0

You need to append a new dictionary to the list, because otherwise you're appending a reference to the old list that has modified values.

Python never implicitly copies objects. When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state. https://stackoverflow.com/a/2465932/4361039

l=[]

for i in range(2):
    id=int(input())
    a=int(input())
    b=int(input())
    o=one(id, {"a": a, "b": b})
    l.append(o)

o.printfun()
ilyankou
  • 1,309
  • 8
  • 13