Skip to content

Instantly share code, notes, and snippets.

@amotl
Last active September 12, 2018 10:13
Show Gist options
  • Save amotl/cacde4c62b191a649a21dda48c4ac1fd to your computer and use it in GitHub Desktop.
Save amotl/cacde4c62b191a649a21dda48c4ac1fd to your computer and use it in GitHub Desktop.
Example demonstrating usage of Python3's "dictionary unpacking" feature. Enjoy!
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Merge dictionaries using Python3's "dictionary unpacking" feature.
# However, this does not do smart things like appropriately merging lists.
# See also https://gist.github.com/amotl/88ea2073d6265e115fe4b14e818549b1
def merge_dicts(defaults, user):
"""
Use dictionary unpacking for merging nested dictionaries,
a feature available since Python3.5.
http://treyhunner.com/2016/02/how-to-merge-dictionaries-in-python/
https://www.python.org/dev/peps/pep-0448/
"""
context = {**defaults, **user}
return context
def example1():
left = {'hello': 'world'}
right = {'foo': 'bar'}
print(merge_dicts(left, right))
def example2():
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():
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-du.py
{'hello': 'world', 'foo': 'bar'}
{'hello': 'world', 'nested': {'key1': 'Räuber', 'key2': 'Hotzenplotz'}, 'foo': 'bar'}
{'hello': 'world', 'nested': {'allowed_ips': ['5.6.7.8/23']}, 'foo': 'bar'}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment