Why does dict.update() overwrite nested dictionaries instead of merging them? [duplicate]

4 weeks ago 22
ARTICLE AD BOX

I’m working on merging configuration dictionaries while building a small script. I expected dict.update() to merge nested dictionaries, but it seems to completely overwrite them instead.

base = { "db": { "host": "localhost", "port": 5432 }, "debug": False } override = { "db": { "port": 5433 } } print("Before update:") print(base) base.update(override) print("\nAfter update:") print(base)

I expected the nested dictionary to be merged so that "db" would still contain both "host" and "port", with "port" changed to 5433.
Instead, the result I get shows the entire nested "db" dictionary is replaced rather than partially merged.

{ "db": { "port": 5433 }, "debug": False }

What is the standard way to perform a “deep merge” of dictionaries in Python without manually iterating through every key?

Read Entire Article