Created
June 13, 2017 11:35
-
-
Save nextkitt/6645462404b6700f928fa2ee07b72df8 to your computer and use it in GitHub Desktop.
merge dict in Python
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 | |
#-*- 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