Why is this loop duplicating the latest entry instead of appending it to the list?

Viewed 74

This is a small snippet of a larger piece of code.

It’s supposed to put data into temp_dict and then add it to the full list of dictionaries list_of_dicts. Then it loops, clears temp_dict, then puts new data into temp_dict and adds that new dictionary to list_of_dicts.

So for this code example:

list_of_dicts = []
blank = {}
temp_dict = {}
 
for i in range(0,5):
    temp_dict = blank
    print(i)
    temp_dict['key'] = i
 
    list_of_dicts.append(temp_dict)
 
print(list_of_dicts)

The result should be:

0
1
2
3
4
[{'key': 0}, {'key':1},{'key':2},{'key':3},{'key':4}]

But instead I get:

0
1
2
3
4
[{'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}, {'key': 4}]

I feel like there’s a really simple fix to this that I’m just not seeing.

2 Answers
temp_dict = blank

That is the reason. You're modifying and reusing the blank object every time through the loop, and your list ends up with multiple identical references to blank.

Just use temp_dict = {} instead.

I found the answer: Python3 dictionary values being overwritten

Always remember: In Python assignment never makes a copy!

Simple fix Just insert a copy:

formatDict[section] = sectionList.copy()    # changed here

Instead of inserting a reference:

formatDict[section] = sectionList

Using .copy() produces the result I need.

temp_dict = blank.copy()

I wasn't aware of how Python "copies" objects.

Related