Python Compare Two Lists of Dictionaries


In this post, we look at how to compare two lists of dictionaries in Python and also print out the differences between the two lists.

The comparison method compares keys and values in the dictionaries.

Also, the ordering of elements does not matter when comparing two lists of dictionaries in Python.

Compare list of dictionaries in Python

if __name__ == '__main__':

    list_1 = [
        {'id': '123-abc', 'name': 'Mike', 'age': 40},
        {'name': 'John', 'age': 34, 'id': '123-efg'},
        {'age': 32, 'id': '123-xyz', 'name': 'Aly'}
    ]

    list_2 = [
        {'name': 'Mike', 'id': '123-abc', 'age': 40},
        {'id': '123-efg', 'age': 34, 'name': 'John'},
        {'id': '123-xyz', 'name': 'Aly', 'age': 32}
    ]

    assert [i for i in list_1 if i not in list_2] == []

In the above code, list_1 and list_2 are equal. That is, each dictionary contains the same items (keys and values) in both lists. The order of elements in each dictionary is irrelevant.


Compare list of dictionaries - print differences

We can also print which dictionary items are different in the lists:

For example:

if __name__ == '__main__':

    list_1 = [
        {'id': '123-abc', 'name': 'Mike', 'age': 40},
        {'id': '123-efg', 'name': 'John', 'age': 24},
        {'id': '123-xyz', 'name': 'Aly', 'age': 35}
    ]

    list_2 = [
        {'id': '123-abc', 'name': 'Mike', 'age': 40},
        {'id': '123-efg', 'name': 'Jon', 'age': 24},
        {'id': '123-xyz', 'name': 'Aly', 'age': 32}
    ]

    for i in list_1:
        if i not in list_2:
            print(i)

Output:

{'id': '123-efg', 'name': 'John', 'age': 24}
{'id': '123-xyz', 'name': 'Aly', 'age': 35}