Created
April 8, 2016 20:00
-
-
Save fuzzy/25262ee968b8cd07d78a5ff98e444474 to your computer and use it in GitHub Desktop.
playing with merging python dictionaries, non destructively
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a recursive function that will merge the two dictionaries. taking lists into account.