Skip to content

Instantly share code, notes, and snippets.

@dunossauro
Created February 25, 2019 19:37
Show Gist options
  • Save dunossauro/c77914f22570a82124f20fe4ca51f331 to your computer and use it in GitHub Desktop.
Save dunossauro/c77914f22570a82124f20fe4ca51f331 to your computer and use it in GitHub Desktop.
Using toolz and dispatcher to merge dicts
from functools import singledispatch
from toolz import merge_with
dict_1 = {
'a': 1,
'b': 1,
'c': [
1, 2, 3, 4
],
'd': {
'e': 7
},
'f': 'test1'
}
dict_2 = {
'a': 2,
'b': 2,
'c': [
5, 6, 7, 8
],
'd': {
'e': 9
},
'f': 'test2'
}
@singledispatch
def merge_function(d1, d2):
...
@merge_function.register(list)
def _(d1, d2):
return d1 + d2
@merge_function.register(int)
def _(d1, d2):
return d1
@merge_function.register(dict)
def _(d1, d2):
return merge_with(merge_interface, d1, d2)
@merge_function.register(str)
def _(d1, d2):
return d1
def merge_interface(x):
dict_1_arg, dict_2_arg = x
return merge_function(dict_1_arg, dict_2_arg)
print(merge_with(merge_interface, dict_1, dict_2))
print(merge_with(merge_interface, dict_2, dict_1))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment