Last active
February 21, 2024 22:11
-
-
Save hadrianw/3843623852ea3294f64f4a3c2213daab to your computer and use it in GitHub Desktop.
Deep merge two Python dicts with dict comprehensions
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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