On sometimes needing to explicitly copy Python dicts

I recently ran into a Python problem that stumped me for a bit. I was looping through a list of dicts and modifying the dicts slightly, then appending them to a new list. But it wasn’t behaving like I thought it would. Despite my loop being extremely simple and easy to step through mentally, my new list wasn’t always receiving the correct dict. I was befuddled.

The problem was that Python was not making a copy of the dict with each loop. I was modifying the same dict over again in each cycle. Apparently, this is because Python doesn’t inherently implicitly copy objects. I needed to explicitly copy the dict, make my changes, and append the modified copy to the new list.

The working version looked like this:

for field in json_list:
    pl = field["Possible Locations"].split(",")
    for location in pl:
        modified_field = field.copy()
        modified_field["PossibleLocations"] = location.strip()
        output.append(modified_field)

The trick here was to add field.copy() to explicitly copy the dict. Problem solved.

This entry was posted in python. Bookmark the permalink. Trackbacks are closed, but you can post a comment.

One Comment

  1. Posted August 16, 2024 at 12:46 pm | Permalink

    Worth keeping in mind that you may need copy.deepcopy() in some situations

Post a Comment

You must be logged in to post a comment.

  • Subscribe to this blog

Skip to toolbar