I want to merge a nested list of dictionaries to single list of a dictionary in python 2.6, Example data - Here is given only two iterations of thousands of iterations.
INPUTJSON=[
{'EXCEPTIONS':
[
{'LASTOCCURED': '2018-03-12 12:11:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'},
{'LASTOCCURED': '2018-03-12 12:11:42', 'COUNT': 10, 'NAME': 'SRV0145GH'}
],
'JVM_NAME': 'TestiingAWS01', 'GCCOUNT': 10},
{'EXCEPTIONS':
[
{'LASTOCCURED': '2018-03-13 12:14:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'},
{'LASTOCCURED': '2018-03-18 12:55:23', 'COUNT': 10, 'NAME': 'SRV0145GH'}
],
'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10}
]
EXPECTED RESULT:
[
{'JVM_NAME':'TestiingAWS01','GCCOUNT':10, 'LASTOCCURED': '2018-03-12 12:11:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-12 12:11:42', 'COUNT': 10, 'NAME': 'SRV0145GH', 'JVM_NAME':'TestiingAWS01','GCCOUNT':10},
{'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10, 'LASTOCCURED': '2018-03-13 12:14:23', 'COUNT': 25, 'NAME': 'CLFRW0134W'}, {'LASTOCCURED': '2018-03-18 12:55:23', 'COUNT': 10, 'NAME': 'SRV0145GH', 'JVM_NAME': 'QAAWS02', 'GCCOUNT': 10}
]
Requesting experts to help me to achieve this so that I could process the final data to sqlite easily.
UPDATE: Thanks, all experts for prompt solutions, consolidating from all answers here I've got a working code for my data by avoiding hardcode "keys" (as there would be 40 keys on each iteration) on python 2.6.
def merge_two_dicts(x, y):
"""Given two dicts, merge them into a new dict as a shallow copy."""
z = x.copy()
z.update(y)
return z
resultlist =[]
for i,v in enumerate(INPUTJSON):
EXCEPTIONS = v["EXCEPTIONS"]
del v["EXCEPTIONS"]
for j,val in enumerate(EXCEPTIONS):
resultlist.append(merge_two_dicts(EXCEPTIONS[j],INPUTJSON[i]))
print resultlist
Can it be compiled in comprehension list using lambda?