Python: Merge two lists of dictionaries

后端 未结 4 1369
自闭症患者
自闭症患者 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 12:54

    One possible way to define it:

    lst1 + [x for x in lst2 if x not in lst1]
    Out[24]: [{'id': 1, 'x': 'one'}, {'id': 2, 'x': 'two'}, {'id': 3, 'x': 'three'}]
    

    Note that this will keep both {'id': 2, 'x': 'three'} and {'id': 2, 'x': 'two'} as you did not define what should happen in that case.

    Also note that the seemingly-equivalent and more appealing

    set(lst1 + lst2)
    

    will NOT work since dicts are not hashable.

提交回复
热议问题