Mappings two list of dict by key

Question:

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?

Asked By: Alain Skyter

||

Answers:

my_list = []
for da in my_list_a:
    # get list of matching rows from list b
    from_b = [db for db in my_list_b if db["code"] == da["code"]]
    if len(from_b) == 0:
        # default if code not found in list b
        my_list.append(da | {"university": ""})
    for db in from_b:
        # add a merged row for each matching row in list b
        my_list.append(da | db)
Answered By: rwhit

I am sure there are more pythonic and efficient ways to do that, anyway:

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})
        
Answered By: Jonathan Ciapetti
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"},
]


new_dictlist = []
for d1 in my_list_a :
    for d2 in my_list_b:
        if d1['code'] == d2['code']:
            new_dictlist.append({'code': d1['code'],'name': d1['name'], 'university': d2['university']})
            
        elif d1['code'] not in [x['code'] for x in my_list_b]:
            data ={'code': d1['code'], 'name': d1['name'],'university': '',}
            if data not in new_dictlist:
                new_dictlist.append(data)
            

print(new_dictlist)
Answered By: Hiral Talsaniya
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.