Skip to content

Instantly share code, notes, and snippets.

@nextkitt
Created June 13, 2017 11:35
Show Gist options
  • Save nextkitt/6645462404b6700f928fa2ee07b72df8 to your computer and use it in GitHub Desktop.
Save nextkitt/6645462404b6700f928fa2ee07b72df8 to your computer and use it in GitHub Desktop.
merge dict in Python
#!/usr/bin/env python
#-*- coding:utf8 -*-
import json
import copy
d1 = {"l1":{"l2":{"l3":{"tps":10,"success":10,"fail":0,"time":20}}}}
d2 = {"l1":{"l2":{"l3":{"tps":20,"success":20,"fail":0,"time":20}}}}
def merge(d, one):
for k,v in one.iteritems():
if not k in d:
d[k] = copy.deepcopy(v)
continue
if isinstance(v, int):
if k == "time":
d[k] = (d[k] + v)/2
continue
d[k] = d[k] + v
continue
if isinstance(v, list):
d[k].extend(copy.deepcop(v))
continue
if isinstance(v, dict):
merge(d[k], v)
def main():
d = {}
merge(d, d1)
merge(d, d2)
print(json.dumps(d1, indent=2))
print(json.dumps(d2, indent=2))
print(json.dumps(d, indent=2))
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment