Skip to content

Instantly share code, notes, and snippets.

@pisceanfoot
Created November 23, 2017 04:48
Show Gist options
  • Save pisceanfoot/3da9416c031f5c38af15f90eae4d8a3c to your computer and use it in GitHub Desktop.
Save pisceanfoot/3da9416c031f5c38af15f90eae4d8a3c to your computer and use it in GitHub Desktop.
merge two dict into one
import copy
def merge(defaultConfig, configs):
new_config = copy.copy(defaultConfig)
if not configs:
return new_config
return _merge(new_config, configs)
def _merge(new_config, configs):
for key in configs:
value = configs[key]
if new_config.has_key(key):
if type(value) == dict:
_merge(new_config[key], value)
else:
new_config[key] = configs[key]
else:
new_config[key] = configs[key]
return new_config
if __name__ == '__main__':
DEFAULT = {
"A": 1,
"B": 2,
"C": {
"C1": 1,
"C3": 3,
"a": {
"b": 1
}
}
}
config = {
# "A": 2,
"B": 3,
"C": {
"C1": 222222,
"C2": '333322',
"a": {
"c": 1
}
}
}
print merge(DEFAULT, config)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment