Last active
July 2, 2024 13:05
-
-
Save daniel-jacob-pearson/56c75766ab176e44123b to your computer and use it in GitHub Desktop.
Deep Merge: transliterated from https://gist.github.com/dpatti/178bd9948518256396ff
This file contains hidden or 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
# Deep merge | |
# | |
# - Write a function that takes two dictionaries and returns a new dictionary | |
# containing the keys and values from both dictionaries. | |
# - Neither input should be modified. | |
# - If the key exists in both dictionaries... | |
# ...merge the values if they are both dictionaries. | |
# ...give the values in the second dictionary (b) precedence otherwise. | |
def merge(a, b): | |
return # replace with your solution | |
# Input for tests | |
a = { | |
"hello": "who?", | |
"foo": { | |
"bar": 1, | |
}, | |
"first": True, | |
} | |
b = { | |
"hello": "world!", | |
"foo": { | |
"baz": 2, | |
}, | |
"second": False, | |
} | |
# Test that the merge gives us the expected results | |
assert merge(a, b) == { | |
"hello": "world!", | |
"foo": { | |
"bar": 1, | |
"baz": 2, | |
}, | |
"first": True, | |
"second": False, | |
} | |
# Test that we have not modified the input | |
assert a == { | |
"hello": "who?", | |
"foo": { | |
"bar": 1, | |
}, | |
"first": True, | |
} | |
assert b == { | |
"hello": "world!", | |
"foo": { | |
"baz": 2, | |
}, | |
"second": False, | |
} | |
print("All tests pass!") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment