Python: Merge two lists of dictionaries

后端 未结 4 1361
自闭症患者
自闭症患者 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

    lst1 = [{"id": 1, "x": "one"}, {"id": 2, "x": "two"}]
    lst2 = [{"id": 2, "x": "two"}, {"id": 3, "x": "three"}]
    
    result = []
    lst1.extend(lst2)
    for myDict in lst1:
        if myDict not in result:
            result.append(myDict)
    print result
    

    Output

    [{'x': 'one', 'id': 1}, {'x': 'two', 'id': 2}, {'x': 'three', 'id': 3}]
    

提交回复
热议问题