for example there is dicA
dicA = {"01Feb":{"a":{"M1":[2,1,3,3],
"M2":[3,5,7,9],
"L3":[1,1,1,1]
},
"b":{"M1":[2,4,8,1],
"M2":[1,1,2,0],
"L3":[3,4,6,8]}
},
"02Feb":{"a":{"M1":[2,3,1,1],
"M2":[6,5,6,9]
},
"b":{"M1":[2,4,8,1],
"M2":[1,1,2,0],
"L3":[3,4,6,8]
},
"c":{"M1":[2,3,1,1],
"M2":[6,5,6,9],
"L3":[0,0,1,1]}
},
"03Feb":{"a":{"M1":[3,3,3,3],
"M2":[5,5,7,7],
"L3":[3,3,3,3]}
}}
this is little bit complicated for me, the list inside has the same length. I want to merge M1 and M2 as M, while just keep L3. It should be like this:
dicA = {{"01Feb":{"a":{"M":[5,6,10,12]},
{"L3":[1,1,1,1]}},
{"b":{"M":[3,5,10,1]},
{"L3":[3,4,6,8]}}},
{"02Feb":{"a":{"M":[8,8,7,10]}},
{"b":{"M":[3,5,10,1]},
{"L3":[3,4,6,8]}},
{"c":{"M":[8,8,7,10]},
{"L3":[0,0,1,1]}}},
{"03Feb":{"a":{"M":[8,8,10,10]},
{"L3":[3,3,3,3]}}}}
Then, I want to merge 'a','b' and 'c'. It should like this finally:
dicA = {{"01Feb":{"M":[8,11,20,13]},
{"L3":[4,5,7,9]}},
{"02Feb":{"M":[19,21,24,21]},
{"L3":[3,4,7,9]}},
{"03Feb":{"M":[8,8,10,10]},
{"L3":[3,3,3,3]}}}
Because I post a similar question before, so you guys may think this is same question. Actually it is a different question which needs to merge multiple nested Dictionaries with Different keys. the link in the comments is show how to merge multiple nested Dictionaries with Same keys.
Here is my solution to combine merge these two situations in this case.
def merge(dictF):
#create two new dict
M_12_merge ={}
abc_merge={}
for key in dictF:
M_12_merge[key]={}
abc_merge[key]={}
for key in dictF:
for subKey in dictF[key]:
M_12_merge[key][subKey]={}
for rekey in M_12_merge:
for sub_rekey in M_12_merge[rekey]:
M_12_merge[rekey][sub_rekey]['M']=[]
# 1. merge sub_sub_key 'M1' and 'M2' under different keys
for key in dictF:
for sub_key in dictF[key]:
numberList=[]
for sub_sub_key in dictF[key][sub_key]:
if 'M' in sub_sub_key:
numberList.append(dictF[key][sub_key][sub_sub_key])
else:
M_12_merge[key][subKey][sub_sub_key]=dictF[key][sub_key][sub_sub_key]
M_12_merge[key][sub_key]['M']=map(sum,zip(*numberList))
# 2. merge sub_key 'a','b' and 'c' under same keys
for key in M_12_merge:
for sub_key in M_12_merge[key]:
for sub_sub_key in M_12_merge[key][sub_key]:
if sub_sub_key in abc_merge[key]:
abc_merge[key][sub_sub_key] = [sum(x) for x in zip(*[abc_merge[key][sub_sub_key], M_12_merge[key][sub_key][sub_sub_key]])]
else:
abc_merge[key][sub_sub_key] = M_12_merge[key][sub_key][sub_sub_key]
return abc_merge
dic = merge(dicA)
print(dic)
Thanks people who vote this question down. Hope this solution can help people who need it. Also, any new ideas is welcomed for this case.
Regards,
D