Skip to content

Instantly share code, notes, and snippets.

@stamat
Last active December 19, 2015 05:19
Show Gist options
  • Save stamat/5903337 to your computer and use it in GitHub Desktop.
Save stamat/5903337 to your computer and use it in GitHub Desktop.
Dictionary deep merge
#Complete dictionary merge
def update(d1, d2):
for k,v in d2.items():
if k in d1 and type(d1[k]) is dict and type(v) is dict:
update(d1[k], v)
else:
d1[k] = v
return d1
#Deep merges two dictionaries to a given level, after that level it only overwrites the values
def updateToLevel(d1, d2, lvl, count = 0):
for k,v in d2.items():
if k in d1 and lvl > count and type(d1[k]) is dict and type(v) is dict:
count += 1
updateToLevel(d1[k], v, lvl, count)
else:
d1[k] = v
return d1
#Deep merges two dictionaries and/or arrays
def updateAll(d1, d2):
if type(d2) is list:
d2 = enumerate(d2)
if type(d2) is dict:
d2 = d2.items()
count = 0
for k,v in d2:
if k in d1:
if type(d1[k]) is dict and type(v) is dict:
updateAll(d1[k], v)
elif type(d1[k]) is list and type(v) is list:
updateAll(d1[k], v)
else:
d1[k] = v
else:
d1[k] = v
return d1
#example
a = {
'a':1,
'b':{
'c':[1,2,[3,45],4,5],
'd':{
'q':1,
'b':{
'q':1,
'b':8},
'c':4
},
'u':'lol',
},
'e':2
}
b = {
'a':1,
'b':{
'c':[2,3,[1]],
'd':{
'q':3,
'b':{'b':3}
}
},
'e':2
}
print updateToLevel(a, b, 1)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment