Skip to content

Instantly share code, notes, and snippets.

@hadrianw
Last active February 21, 2024 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hadrianw/3843623852ea3294f64f4a3c2213daab to your computer and use it in GitHub Desktop.
Save hadrianw/3843623852ea3294f64f4a3c2213daab to your computer and use it in GitHub Desktop.
Deep merge two Python dicts with dict comprehensions
def merge(original: dict, update: dict):
return {
k: (merge(original[k], v) if M and isinstance(v, dict) and k in original else v)
for d, M in ((original, False), (update, True))
for k, v in d.items()
}
if __name__ == "__main__":
base = {"foo": 1, "bar": {"abc": 123, "def": 456}, "baz": 2}
ext = {"foo": 11, "bar": {"abc": 321}}
assert merge(base, ext) == {
"foo": 11,
"bar": {"abc": 321, "def": 456},
"baz": 2,
}, f"merge({base}, {ext})"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment