Reputation: 37
I have two lists of dictionaries and I want to combine or merge both of them. The obstruction here is I want to combine them based on the key value and this key value is different in every iteration, they are not fixed, how do I accomplish this? Following are the two Lists of Dictionaries I have which needs to be merged.
l1 = [
{'Fvcm':{
'name' :'FVCM',
'size' : 8,
'Type' : 'Z'
}
},
{'RPZM':{
'name' :'RPZM',
'size' : 8,
'Type' : 'R'
},
},
{'ZAN':{
'name' :'ZAN',
'size' : 8,
'Type' : 'P'
}
}
]
l2 = [
{'Fvcm':{
'name' :'FVCM',
'map' : 'Prim1'
}
},
{'RPZM':{
'name' :'RPZM',
'map' : 'Prim2'
},
},
{'ZAN':{
'name' :'ZAN',
'map' : 'Prim3'
}
}
]
and I want the final result to look like:
l3 = [
{'Fvcm':{
'name' :'FVCM',
'map' : 'Prim1',
'size' : 8,
'Type' : 'Z'
}
},
{'RPZM':{
'name' :'RPZM',
'map' : 'Prim2',
'size' : 8,
'Type' : 'R'
},
},
{'ZAN':{
'name' :'ZAN',
'map' : 'Prim3',
'size' : 8,
'Type' : 'P'
}
}
]
Thanks in advance!
Upvotes: 0
Views: 50
Reputation: 18106
You can use update, to merge 2 dictionaries together. That requires to modify your nested list-of-dicts structure into non nested dicts:
d1 = {k: v for item in l1 for k, v in item.items()} # regular k,v dict
d2 = {k: v for item in l2 for k, v in item.items()} # same
_ = [d1[k].update(v) for (k, v) in d2.items()] # update each key in d1 with its corresponding value from d2
print(d1)
Out:
{'Fvcm': {'name': 'FVCM', 'size': 8, 'Type': 'Z', 'map': 'Prim1'}, 'RPZM': {'name': 'RPZM', 'size': 8, 'Type': 'R', 'map': 'Prim2'}, 'ZAN': {'name': 'ZAN', 'size': 8, 'Type': 'P', 'map': 'Prim3'}}
Upvotes: 1