Skip to content

Instantly share code, notes, and snippets.

@fuzzy
Created April 8, 2016 20:00
Show Gist options
  • Save fuzzy/25262ee968b8cd07d78a5ff98e444474 to your computer and use it in GitHub Desktop.
Save fuzzy/25262ee968b8cd07d78a5ff98e444474 to your computer and use it in GitHub Desktop.
playing with merging python dictionaries, non destructively
# This works fine
>>> a = {'foo': 'bar'}
>>> b = {'baz': 'qux'}
>>> c = a.copy()
>>> c.update(b)
>>> c
{'foo': 'bar', 'baz': 'qux'}
# This starts to show us some issues
>>> a = {'foo': 'bar'}
>>> b = {'foo': 2}
>>> c = a.copy()
>>> c.update(b)
>>> c
{'foo': 2}
# We see no type checking (even optionally) to ensure safety
# We also see the following:
>>> a = {'foo': ['bar']}
>>> b = {'foo': ['baz', 'qux']}
>>> c = a.copy()
>>> c.update(b)
>>> c
{'foo': ['baz', 'qux']}
# A list type is appendable, and I see no reason why it should
# be that way when merging dictionaries. Perhaps a merge() method
# to the dict object would be appropriate leaving update()'s to
# continue behaving as it does
@fuzzy
Copy link
Author

fuzzy commented Apr 8, 2016

import sys
from pprint import pprint

def mergeDicts(a, b):
    c = b.copy()
    for k in a.keys():
        if k not in c.keys():
            c[k] = a[k]
        elif isinstance(a[k], (list, tuple)):
                for i in a[k]:
                    if i not in c[k]:
                        c[k].append(i)
        elif isinstance(a[k], dict):
            c[k] = mergeDicts(a[k], c[k])
    return c

if __name__ == '__main__':
    pprint(mergeDicts({'foo': ['bar']}, {'foo': ['baz'], 'qux': 'yes'}))

This is a recursive function that will merge the two dictionaries. taking lists into account.

$ python dmerge.py
{'foo': ['baz', 'bar'], 'qux': 'yes'}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment