bhylu.com

Advertisements

Copy Dictionaries

A dictionary's copy method makes a shallow outer copy. Nested mutable values are still shared unless you copy or rebuild them too.

Understand the idea

This matters for configuration, user records, and response transformations. A top-level assignment in the copy is independent, while an append inside a shared list is not. deepcopy can help for suitable pure-data graphs, but a clear ownership model is better than copying everything without understanding why.

Where to try it

Open this example with Try in playground. The code loads as editable text and does not run until you select Run. The first run downloads Python. Each run starts fresh; temporary files created by a script are not files on your PC.

A worked example

Python

original = {"name": "Mira", "tags": ["web"]}
copied = original.copy()
copied["name"] = "Dev"
copied["tags"].append("python")
print(original)

Read the result

The original name remains Mira, but its tags include web and python.

Try one change

Make tags independent in a deliberate copy and verify that appending no longer changes the source record.