How to merge lists of dictionaries

后端 未结 4 1916
情歌与酒
情歌与酒 2020-12-03 11:49

With lists of dictionaries such as the following:

user_course_score = [
    {\'course_id\': 1456, \'score\': 56}, 
    {\'course_id\': 316, \'score\': 71}
]
         


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-03 11:56

    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.

提交回复
热议问题