Python: Merge two lists of dictionaries

后端 未结 4 1375
自闭症患者
自闭症患者 2020-12-16 12:30

Given two lists of dictionaries:

>>> lst1 = [{id: 1, x: \"one\"},{id: 2, x: \"two\"}]
>>> lst2 = [{id: 2, x: \"two\"}, {id: 3, x: \"three\"         


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-16 13:12

    Perhaps the simplest option

    result = {x['id']:x for x in lst1 + lst2}.values()
    

    This keeps only unique ids in the list, not preserving the order though.

    If the lists are really big, a more realistic solution would be to sort them by id and merge iteratively.

提交回复
热议问题