Last active
April 7, 2018 06:57
-
-
Save larryhou/76869f0b025fdbfcd933c9d715433166 to your computer and use it in GitHub Desktop.
Merge two dict object deeply
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
| #!/usr/bin/env python | |
| def merge_dict(data, target): | |
| for key, value in data.iteritems(): | |
| node = target.get(key) | |
| if not node or type(value) != type(node): | |
| target[key] = value # add new value or replace value when type conficts | |
| continue | |
| if isinstance(value, dict): | |
| merge_dict(value, node) # iterate merge dict-type value | |
| continue | |
| if isinstance(value, list): | |
| for item in value: # merge list-type value | |
| if not node.__contains__(item): node.append(item) | |
| else: | |
| target[key] = value # replace value for simple type |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment