Skip to content

Instantly share code, notes, and snippets.

@yosukesan
Last active February 21, 2023 05:57
Show Gist options
  • Save yosukesan/074465a7ada7c5185b0e41fa371d02b3 to your computer and use it in GitHub Desktop.
Save yosukesan/074465a7ada7c5185b0e41fa371d02b3 to your computer and use it in GitHub Desktop.
def deep_union(a, b):
if not isinstance(a, dict):
TypeError("a is not dict")
if not isinstance(b, dict):
TypeError("b is not dict")
if a == b:
return a
if len(a.keys()) < len(a.keys()):
a, b = b, a
for key in b.keys():
if key in a.keys():
a[key] = deep_union(a[key], b[key])
else:
a[key] = b[key]
return a
if __name__=="__main__":
d1 = {'a': 1, 'b':{'aa': 11, 'bb': 23}}
d2 = {'z': 9, 'b':{'cc': 22, 'dd': 343, 'yyy': {'ddd': 324}}, 'c': 2}
# test1
d1 = deep_union(d1, d2)
print(d1)
# test2
d1 = d1 | d2
d1 = deep_union(d1, d2)
print(d1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment