Skip to content

Instantly share code, notes, and snippets.

@milanboers
Created November 12, 2020 12:56
Show Gist options
  • Save milanboers/a8bb8b81b1c3fb3eb86ee2d9ea4bd5b2 to your computer and use it in GitHub Desktop.
Save milanboers/a8bb8b81b1c3fb3eb86ee2d9ea4bd5b2 to your computer and use it in GitHub Desktop.
Deep merge dicts in Python
def deep_merge(dict1: dict, dict2: dict) -> dict:
""" Merges two dicts. If keys are conflicting, dict2 is preferred. """
def _val(v1, v2):
if isinstance(v1, dict) and isinstance(v2, dict):
return deep_merge(v1, v2)
return v2 or v1
return {k: _val(dict1.get(k), dict2.get(k)) for k in dict1.keys() | dict2.keys()}
@PrefixCoder
Copy link

Thank you!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment