How do I Concatenate or Combine the dictionary of same data to One

Issue

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?

Solution

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",
}

Answered By – Andrej Kesely

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published