Skip to content

Instantly share code, notes, and snippets.

@larryhou
Last active April 7, 2018 06:57
Show Gist options
  • Select an option

  • Save larryhou/76869f0b025fdbfcd933c9d715433166 to your computer and use it in GitHub Desktop.

Select an option

Save larryhou/76869f0b025fdbfcd933c9d715433166 to your computer and use it in GitHub Desktop.
Merge two dict object deeply
#!/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