Skip to content

Instantly share code, notes, and snippets.

@amotl
Last active July 26, 2022 02:28
Show Gist options
  • Save amotl/88ea2073d6265e115fe4b14e818549b1 to your computer and use it in GitHub Desktop.
Save amotl/88ea2073d6265e115fe4b14e818549b1 to your computer and use it in GitHub Desktop.
Example demonstrating usage of Python's "deepmerge" package. Enjoy!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Merge dictionaries in a smart way using the "deepmerge" package.
# Works with Python2 and Python3.
# See also https://gist.github.com/amotl/cacde4c62b191a649a21dda48c4ac1fd
# https://pypi.org/project/deepmerge/
# pip install deepmerge
from deepmerge import Merger
def merge_dicts(*dicts):
"""
Utility function for merging nested dictionaries in a smart way.
"""
merger = Merger([
(list, ["append"]),
(dict, ["merge"])
],
["override"],
["override"]
)
return merger.merge(*dicts)
def example1():
"""
A very basic example
"""
left = {'hello': 'world'}
right = {'foo': 'bar'}
print merge_dicts(left, right)
def example2():
"""
Merge nested dictionaries
"""
left = {'hello': 'world', 'nested': {'key1': 'value1', 'key2': 'value2'}}
right = {'foo': 'bar', 'nested': {'key1': u'Räuber', 'key2': 'Hotzenplotz'}}
print merge_dicts(left, right)
def example3():
"""
Merge nested dictionaries containing lists
"""
left = {'hello': 'world', 'nested': {'allowed_ips': ['1.2.3.4/25']}}
right = {'foo': 'bar', 'nested': {'allowed_ips': ['5.6.7.8/23']}}
print merge_dicts(left, right)
if __name__ == '__main__':
example1()
example2()
example3()
$ ./dictmerge-dm.py
{'foo': 'bar', 'hello': 'world'}
{'foo': 'bar', 'hello': 'world', 'nested': {'key2': 'Hotzenplotz', 'key1': u'R\xe4uber'}}
{'foo': 'bar', 'hello': 'world', 'nested': {'allowed_ips': ['1.2.3.4/25', '5.6.7.8/23']}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment