循环查找两个字典中的匹配值

2024-03-29 08:28:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个不同的文件,由字典组成。我尝试只循环遍历第一个字典文件中的键('name')值,并将它们与第二个文件匹配。我似乎得到了错误的输出,因为它循环通过键'name'和'size'。我已经研究过几种方法来做这件事,但我不想把我的字典转换成一套。我想打印出“匹配”或“不匹配”。到目前为止,我已经做了以下工作:

def compare_files():

with open('new.json', 'r') as current_data_file, open('old.json','r') as pre_data_file:

    for current_data, previous_data in zip(current_data_file, pre_data_file):

        data_current = json.loads(current_data)
        data_previous = json.loads(previous_data)



        for key, value in data_current.items():
            if value not in data_previous:
                print "No Match"
            else:
                print "Match"

这是我正在加载的两个json文件:

在旧.json在

^{pr2}$

在新建.json在

{"name": "a.json", "size": 1000}
{"name": "b.json", "size": 1000}
{"name": "c.json", "size": 1000}

当前数据为:

{u'size': 1000, u'name': u'a.json'}
{u'size': 1000, u'name': u'b.json'}
{u'size': 1000, u'name': u'c.json'}

以前的数据是:

{u'size': 1000, u'name': u'd.json'}
{u'size': 1000, u'name': u'c.json'}
{u'size': 1000, u'name': u'b.json'}

输出:

No Match
No Match
No Match
No Match
No Match
No Match

我的预期产出是:

No Match
Match
Match

b.json和c.json都存在,但a.json和d.json没有。在


Tags: 文件nonameinjsondatasize字典
3条回答

为了避免麻烦,您可以使用pandas(第三方库)直接读取数据,并且可以非常容易地进行分析

import pandas as pd

df=pd.DataFrame('new.json')
df2=pd.DataFrame('old.json')

df.name.isin(df2.name).replace({False:'No Match',True:'Match'}).tolist()

输出

^{pr2}$

对于每个“当前”项目,您必须与所有“先前”项目进行比较,而不仅仅是同一位置的项目(这是“zip”将帮助您实现的目标)

data_current = [{"name": "d.json", "size": 1000},
                {"name": "c.json", "size": 1000},
                {"name": "b.json", "size": 1000}]

data_previous = [{"name": "a.json", "size": 1000},
                 {"name": "b.json", "size": 1000},
                 {"name": "c.json", "size": 1000}]

for current in data_current:
    result = "No Match"
    for previous in data_previous:
        if current["name"] == previous["name"]:
            result = "Match"
    print(result)

编辑:如果你想检查当前项与上一项,也检查前一项与当前项,你可以做以下操作(我在印刷品中添加了一些文本,以澄清发生了什么)

^{pr2}$

你的代码有一些问题。在

  1. 当您执行if value not in data_previous:时,您实际上要检查value是否在data_previous键中,而不是在其值中。

  2. 当你做zip(current_data_file, pre_data_file)时,你实际上是在看两个字典的对应的对。这里有3个字典,每个字典中有2个键,这就是为什么有6个输出行而不是3个输出行。换句话说,您是成对查找数据,而不是将数据中的每个字典与其他数据中的所有字典进行比较。

下面是一个示例代码:

def compare_files():
    with open('new.json', 'r') as current_data_file, open('old.json','r') as pre_data_file:
        # load both data 
        data_currents = [json.loads(line) for line in current_data_file]
        data_previous = [json.loads(line) for line in pre_data_file]

        # store the previous names for convenient lookup
        pre_names = set([data["name"] for data in data_previous])

        # loop through all current data for matching names
        for data in data_currents:
            print("Match" if data["name"] in pre_names else "No Match")

相关问题 更多 >