Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

So sánh hiệu quả hai List of Dictionaries trong Python - Tìm khác biệt nhanh chóng

Bài viết trình bày cách so sánh hai list of dictionaries trong Python và in ra các khác biệt.

Phương pháp so sánh kiểm tra cả keys và values trong dictionaries.

Thứ tự phần tử không quan trọng khi so sánh hai list of dictionaries.

So sánh list of dictionaries trong 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] == []

Trong code trên, list_1 và list_2 bằng nhau. Mỗi dictionary chứa cùng items (keys và values) trong cả hai list. Thứ tự key trong mỗi dictionary không quan trọng.

So sánh list of dictionaries - in ra khác biệt

Có thể in ra dictionary items khác nhau giữa hai list:

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)

Kết quả:

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

Cách viết khác (hàm reusable):

def compare_two_lists(list1: list, list2: list) -> bool:
    """So sánh hai list và log sự khác biệt.
    :param list1: list đầu tiên.
    :param list2: list thứ hai.
    :return: True nếu không có khác biệt.
    """
    diff = [i for i in list1 + list2 if i not in list1 or i not in list2]
    result = len(diff) == 0
    if not result:
        print(f'There are {len(diff)} differences:\n{diff[:5]}')
    return result

So sánh dùng Pandas DataFrame

Ví dụ so sánh hai list dùng Pandas DataFrame:

from pandas import DataFrame
import pandas as pd

def compare_two_lists(list1: list, list2: list) -> bool:
    df1 = pd.DataFrame(list1)
    df2 = pd.DataFrame(list2)
    diff = dataframe_difference(df1, df2)
    result = len(diff) == 0
    if not result:
        print(f'There are {len(diff)} differences:\n{diff.head()}')
    return result

def dataframe_difference(df1: DataFrame, df2: DataFrame) -> DataFrame:
    """Tìm rows khác nhau giữa hai DataFrame."""
    comparison_df = df1.merge(df2, indicator=True, how='outer')
    diff_df = comparison_df[comparison_df['_merge'] != 'both']
    return diff_df