Comparing 2 lists consisting of dictionaries with unique keys in python

前端 未结 6 897
遥遥无期
遥遥无期 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:14

    The following compares the dictionaries and prints the non-equal items:

    for d1, d2 in zip(list_1, list_2):
        for key, value in d1.items():
            if value != d2[key]:
                print key, value, d2[key]
    

    Output: key2 BBB DDD. By using zip we can iterate over two dictionaries at a time. We then iterate over the items of the first dictionary and compare the value with the corresponding value in the second dictionary. If these are not equal, then we print the key and both values.

提交回复
热议问题