Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Mappings two list of dict by key

I have two list of dict with Python and I have a problem I don’t know how to solve it?

my_list_a = [
             {"code": "A", "name": "Mr A"},
             {"code": "B", "name": "Mrs B"},
             {"code": "C", "name": "Mrs C"}
]

my_list_b = [
             {"code": "A", "university": "Oxford"},
             {"code": "B", "university": "Stanford"},
             {"code": "B", "university": "Harvard"},
]

# my expected result is:
my_list = [
             {"code": "A", "name": "Mr A", "university": "Oxford"},
             {"code": "B", "name": "Mrs B", "university": "Stanford"},
             {"code": "B", "name": "Mrs B", "university": "Harvard"},
             {"code": "C", "name": "Mrs C", "university": ""},
]

As seen, I need to map two data list together by key is "code". And if my_list_b not exist "code", it will "" all field

I don’t know How do I make it right?. Is there any way I can get the expected result?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

my_list = []
my_list_b_codes = [item["code"] for item in my_list_b]
for item_a in my_list_a:
    if item_a["code"] not in my_list_b_codes:
        my_list.append({**item_a, "university": ""})
    else:
        for item_b in my_list_b:
            if item_a["code"] == item_b["code"]:
                my_list.append({**item_a, **item_b})
        
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading