Comparing 2 lists consisting of dictionaries with unique keys in python

前端 未结 6 894
遥遥无期
遥遥无期 2020-12-02 15:25

I have 2 lists, both of which contain same number of dictionaries. Each dictionary has a unique key. There is a match for each dictionary of the first list in the second lis

6条回答
  •  悲哀的现实
    2020-12-02 16:22

    The fastest and most comprehensive way would be, to use two sets of tuples:

    set_list1 = set(tuple(sorted(d.items())) for d in list1)
    set_list2 = set(tuple(sorted(d.items())) for d in list2)
    

    Find overlapping using intersection:

    set_overlapping = set_list1.intersection(set_list2)
    

    Find difference using symmetric_difference

    set_difference = set_list1.symmetric_difference(set_list2)
    

    Convert tuple back to dict

     for tuple_element in set_difference:
         list_dicts_difference.append(dict((x, y) for x, y in tuple_element))
    

提交回复
热议问题