How to merge lists of dictionaries

Here’s a possible solution:

def merge_lists(l1, l2, key):
    merged = {}
    for item in l1+l2:
        if item[key] in merged:
            merged[item[key]].update(item)
        else:
            merged[item[key]] = item
    return merged.values()

courses = merge_lists(user_course_score, courses, 'course_id')

Produces:

[{'course_id': 1456, 'name': 'History', 'score': 56},
 {'course_id': 316, 'name': 'Science', 'score': 71},
 {'course_id': 926, 'name': 'Geography'}]

As you can see, I used a dictionary (‘merged’) as a halfway point. Of course, you can skip a step by storing your data differently, but it depends also on the other uses you may have for those variables.

All the best.

Leave a Comment