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?

>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})
        

Leave a Reply