Skip to content

Instantly share code, notes, and snippets.

@daniel-jacob-pearson
Last active July 2, 2024 13:05
Show Gist options
  • Save daniel-jacob-pearson/56c75766ab176e44123b to your computer and use it in GitHub Desktop.
Save daniel-jacob-pearson/56c75766ab176e44123b to your computer and use it in GitHub Desktop.
Deep Merge: transliterated from https://gist.github.com/dpatti/178bd9948518256396ff
# 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