Last active
January 27, 2016 20:29
-
-
Save saurabh-hirani/6f3f5d119076df70e0da to your computer and use it in GitHub Desktop.
Merge data structures in python
This file contains 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
import json | |
import itertools | |
from mergedict import ConfigDict | |
# minor changes to original code at http://stackoverflow.com/questions/19378143/python-merging-two-arbitrary-data-structures | |
def merge(a, b): | |
if isinstance(a, dict) and isinstance(b, dict): | |
d = dict(a) | |
d.update({k: merge(a.get(k, None), b[k]) for k in b}) | |
return d | |
if isinstance(a, list) and isinstance(b, list): | |
is_a_nested = any(x for x in a if isinstance(x, list) or isinstance(x, dict)) | |
is_b_nested = any(x for x in b if isinstance(x, list) or isinstance(x, dict)) | |
if is_a_nested or is_b_nested: | |
return [merge(x, y) for x, y in itertools.izip_longest(a, b)] | |
else: | |
return a + b | |
return a if b is None else b | |
ds1 = { | |
"name": "saurabh", | |
"values": ["a", "b", "c"], | |
"in_ds1": "here", | |
"clean_nesting": { | |
"l1": { | |
"l2": { | |
"l3": { | |
"l4": { | |
"what": [{"age": "2"}] | |
} | |
} | |
} | |
} | |
}, | |
"arbitary_nesting": { | |
"k1": { | |
"k2": { | |
"k3": [1,2,3] | |
} | |
} | |
} | |
} | |
ds2 = { | |
"name": "whoknows", | |
"values": ["d", "e", "f"], | |
"in_ds2": "there", | |
"clean_nesting": { | |
"l1": { | |
"l2": { | |
"l3": { | |
"l4": { | |
"what": [{"name": "1"}, "12"] | |
} | |
} | |
} | |
} | |
}, | |
"arbitary_nesting": { | |
"k1": { | |
"k2": { | |
"k4": {"k5": "k6"} | |
} | |
} | |
} | |
} | |
ds3 = { | |
'a': 1, | |
'b': [1,2,3], | |
'c': { | |
'd': [ | |
[3, 4], | |
4, | |
{ | |
'a': { | |
'b': [11,12,13] | |
} | |
} | |
] | |
} | |
} | |
ds4 = { | |
'a': 2, | |
'b': [4,5,6], | |
'c': { | |
'd': [ | |
[1,2,3], | |
2, | |
{ | |
'a': { | |
'b': [14,15] | |
} | |
}, | |
] | |
} | |
} | |
print "------------" | |
print json.dumps(ds1, indent=2) | |
print "------------" | |
print json.dumps(ds2, indent=2) | |
print "------------" | |
print json.dumps(merge(ds1, ds2), indent=2) | |
print "================" | |
print json.dumps(ds3, indent=2) | |
print "------------" | |
print json.dumps(ds4, indent=2) | |
print "------------" | |
print json.dumps(merge(ds3, ds4), indent=2) | |
print "================" | |
print json.dumps(merge([1,2,3], [4,5,6]), indent=2) | |
print "----------" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment