python - 比较 python 中的两个嵌套 dictionaries 并找到另一个 dictionary 中不存在的记录

我编写了代码,将记录信息从旧 csv 文件的文件夹中提取到 dictionary A 中,将新 csv 文件的文件夹中的记录信息提取到 dictionary B 中。 dictionaries 每个看起来如下所示,具有不同的文件名每条记录表明它来自哪里的记录(或行):

{'MC1003-1513846743.67153296': {'row': 2, 'record': ['MC1003-1', '5138467', '43.67', '15', '', '', '', '', '', '', '', '', '', '', '3296'], 'file_name': 'Timecard-MC1003-1-20220425103004.csv'}, 'MC1003-1546339635.95153296': {'row': 3, 'record': ['MC1003-1', '5463396', '35.95', '15', '', '', '', '', '', '', '', '', '', '', '3296'], 'file_name': 'Timecard-MC1003-1-20220425103004.csv'}

我正在尝试比较两个 dictionaries ,每个都包含来自旧文件夹和新文件夹的一千多个不同的记录。查找 dictionary A 中的记录是否存在于 dictionary B 中的最佳方法是什么,并以相反的方式执行相同的操作,即检查 dictionary B 中的记录是否存在于 dictionary A 中。有人可以帮帮我吗!我正在努力寻找解决方案?我在下面写的代码理论上应该查看dictionary B中的所有记录,将它们中的每一个与dictionary A中的记录进行比较,如果与正在比较的特定记录不匹配则输出记录。但是,我只想从 dictionary A 输出一条记录,前提是它与 dictionary B 中的任何记录都不匹配。现在,它出于某种原因输出了所有记录。请让我知道我做错了什么?这里 dir_A_dict 和 dir_B_dict 是我读过的 dictionaries 。

for a in dir_A_dict.keys():
    row_a = dir_A_dict[a].get('row')
    result_a = dir_A_dict[a].get('record')
    name_a = dir_A_dict[a].get('file_name')
    for b in dir_B_dict.keys():
        row_b = dir_B_dict[b].get('row')
        result_b = dir_B_dict[b].get('record')
        name_b = dir_B_dict[b].get('file_name')
        
        if result_a != result_b:
            print("Record", result_a,"in file",name_a, "is different from", result_b,"in file", name_b)

这段代码的输出结果是这样的。在这种情况下,由于 dictionary A 中的记录明显存在于 dictionary B 中,代码应该转到 dictionary A 中的下一条记录,并查找该记录是否也存在于 dictionary B 中:

Record ['MC1003-1', '5138467', '43.67', '15', '', '', '', '', '', '', '', '3296'] in file Timecard-MC1003-1-20220425100254-Reported.csv is different from ['MC1003-1', '5138467', '43.67', '15', '', '', '', '', '', '', '', '', '', '', '3296'] in file Timecard-MC1003-1-20220425103004.csv
Record ['MC1003-1', '5138467', '43.67', '15', '', '', '', '', '', '', '', '3296'] in file Timecard-MC1003-1-20220425100254-Reported.csv is different from ['MC1003-1', '5463396', '35.95', '15', '', '', '', '', '', '', '', '', '', '', '3296'] in file Timecard-MC1003-1-20220425103004.csv

回答1

只需将 dict 中的所有记录堆成一个集合:

aset = set()
for v in adict.values():
    [aset.add(record) for record in v['record']]

# ... build other set

然后你有一个简单的方法来查询哪些记录属于 dictionary A 而不在 dictionary B 中:

# aset is generated from dictionary A
# bset is generated from dictionary B

in_a_not_b = aset - bset

相似文章

随机推荐

最新文章