Search code examples
pythonlistdictionarymerge

Merge 2 dictionary lists in order


I have these 2 lists of dictionaries:

[{'type': 'excel_macro', 'Name': 'Nuevo Diseño de Registro de nominas.xlsm'}, 
 {'type': 'pdf', 'Name': 'Presentación oferta comercial Nómina.pdf'}
]

[{'id': 35630898}, {'id': 35630899}]

and I want it to be like this:

[{'type': 'excel_macro', 'Name': 'Nuevo Diseño de Registro de nominas.xlsm', 'id': 35630898}, 
 {'type': 'pdf', 'Name': 'Presentación oferta comercial Nómina.pdf', 'id': 35630899}
]

That is, I want to merge the dictionaries of the lists in order, including the 'id' within the corresponding dictionary

I've looked for how to do it but I haven't found exactly this. I appreciate the help.


Solution

  • Here's a way:

    d1 = [{'type': 'excel_macro', 'Name': 'Nuevo Diseño de Registro de nominas.xlsm'}, {'type': 'pdf', 'Name': 'Presentación oferta comercial Nómina.pdf'}]
    d2 = [{'id': 35630898}, {'id': 35630899}]
    
    # union operator(|) supported for dicts as of Python 3.9.
    result = [a | b for a, b in zip(d1, d2)]
    print(result)
    

    Output:

    [{'type': 'excel_macro', 'Name': 'Nuevo Diseño de Registro de nominas.xlsm', 'id': 35630898}, {'type': 'pdf', 'Name': 'Presentación oferta comercial Nómina.pdf', 'id': 35630899}]