Appending a dict inside a loop gives me the same row repeated 40 times Help
I build a dict outside the loop, update two keys on each pass, then append it to a list. At the end every entry in the list is identical and equal to the last row. If I print inside the loop the values are correct on each pass. I assume this is something about how Python stores things but I do not have the vocabulary for it.
@goroutine_gil · 2mo ago · 3 replies
You appended the same dictionary forty times. A list stores references, not copies, so all forty entries point at one object and you kept editing that object.
Fix: create the dict inside the loop. First line of the loop body is
record = {}, fill it, append it.If you genuinely need a template each time,
dict(template)ortemplate.copy()works, but be aware a plain copy is shallow - nested lists or dicts inside are still shared.copy.deepcopyhandles that and you rarely need it.You now have the vocabulary: mutable objects, references, aliasing. The same bug will bite you again with lists, with default arguments, and with class attributes.
Reply
Report
@sheetsmith · 2mo ago
Moving the dict inside the loop fixed it instantly. The default arguments thing sounds like it is going to get me next.
Reply
Report
@goroutine_gil · 2mo ago
It will.
def f(items=[])is the classic. That empty list is created once when the function is defined, not on each call.Reply
Report