I have the below set of 7 Dictionaries
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,1)':'Unmarked'}
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,2)':'Unmarked'}
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,3)':'Present'}
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,4)':'Unmarked'}
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,5)':'Unmarked'}
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,6)':'Absent'}
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,7)':'Unmarked'}
I want to convert into the below format.
{'empid':785, 'empname':'Ibrahim', 'date(2022,5,1)':'Unmarked', 'date(2022,5,2)':'Unmarked', 'date(2022,5,3)':'Present', 'date(2022,5,4)':'Unmarked', 'date(2022,5,5)':'Unmarked', 'date(2022,5,6)':'Absent', 'date(2022,5,7)':'Unmarked'}
How can i do this?
CodePudding user response:
def Merge(a,b,c,d,e,f,g):
res = a | b | c | d | e | f | g
return res
a = {'empid':785, 'empname':'Ibrahim', 'date(2022,5,1)':'Unmarked'}
b = {'empid':785, 'empname':'Ibrahim', 'date(2022,5,2)':'Unmarked'}
c = {'empid':785, 'empname':'Ibrahim', 'date(2022,5,3)':'present'}
d = {'empid':785, 'empname':'Ibrahim', 'date(2022,5,4)':'Unmarked'}
e = {'empid':785, 'empname':'Ibrahim', 'date(2022,5,5)':'Unmarked'}
f = {'empid':785, 'empname':'Ibrahim', 'date(2022,5,6)':'Absent'}
g = {'empid':785, 'empname':'Ibrahim', 'date(2022,5,7)':'Unmarked'}
result = Merge(a,b,c,d,e,f,g)
CodePudding user response:
Another method:
dcts = [
{"empid": 785, "empname": "Ibrahim", "date(2022,5,1)": "Unmarked"},
{"empid": 785, "empname": "Ibrahim", "date(2022,5,2)": "Unmarked"},
{"empid": 785, "empname": "Ibrahim", "date(2022,5,3)": "Present"},
{"empid": 785, "empname": "Ibrahim", "date(2022,5,4)": "Unmarked"},
{"empid": 785, "empname": "Ibrahim", "date(2022,5,5)": "Unmarked"},
{"empid": 785, "empname": "Ibrahim", "date(2022,5,6)": "Absent"},
{"empid": 785, "empname": "Ibrahim", "date(2022,5,7)": "Unmarked"},
]
out = {k: v for d in dcts for k, v in d.items()}
print(out)
Prints:
{
"empid": 785,
"empname": "Ibrahim",
"date(2022,5,1)": "Unmarked",
"date(2022,5,2)": "Unmarked",
"date(2022,5,3)": "Present",
"date(2022,5,4)": "Unmarked",
"date(2022,5,5)": "Unmarked",
"date(2022,5,6)": "Absent",
"date(2022,5,7)": "Unmarked",
}
CodePudding user response:
from functools import reduce
lst = [{'empid': 785, 'empname': 'Ibrahim', 'date(2022,5,1)': 'Unmarked'},
{'empid': 785, 'empname': 'Ibrahim', 'date(2022,5,2)': 'Unmarked'},
{'empid': 785, 'empname': 'Ibrahim', 'date(2022,5,3)': 'Present'},
{'empid': 785, 'empname': 'Ibrahim', 'date(2022,5,4)': 'Unmarked'},
{'empid': 785, 'empname': 'Ibrahim', 'date(2022,5,5)': 'Unmarked'},
{'empid': 785, 'empname': 'Ibrahim', 'date(2022,5,6)': 'Absent'},
{'empid': 785, 'empname': 'Ibrahim', 'date(2022,5,7)': 'Unmarked'}]
def fun(dct1, dct2):
res = dct1.copy()
for key, value in dct2.items():
if key not in dct1:
res[key] = value
return res
reduce(fun, lst)