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

时间:2018-12-12 15:05:51

标签: python json python-2.7 dictionary

我有两个不同的文件,其中包括字典。我试图只遍历字典的第一个文件中的键(“名称”),值,并将其与第二个文件匹配。我似乎得到了错误的输出,因为它在两个键“名称”和“大小”之间循环。我已经看过几种方法,但是我不想将字典转换为集合。我希望能够打印出“匹配”或“不匹配”。到目前为止,我已完成以下操作:

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文件:

old.json

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

new.json

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

data_current为:

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

data_previous是:

{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不存在。

3 个答案:

答案 0 :(得分:2)

为了避免麻烦,您可以使用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()

输出

['No Match', 'Match', 'Match']

答案 1 :(得分:0)

您的代码中有几个问题。

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

    < / li>
  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")

答案 2 :(得分:0)

对于每个“当前”项目,您都必须与所有“先前”项目进行比较,而不仅仅是与处于相同位置的项目进行比较(“ 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)

编辑:如果要检查当前项目与以前的项目以及之前项目与当前的项目,可以执行以下操作(我在打印件中添加了一些文本以阐明正在发生的事情)

checks_to_run = [
    {
        "from": data_current,
        "from_name": "current", #Added for transparency
        "against": data_previous,
        "against_name": "previous", #Added for transparency
    },
    {
        "from": data_previous,
        "from_name": "previous", #Added for transparency
        "against": data_current,
        "against_name": "current", #Added for transparency
    }
]

for check_to_run in checks_to_run:
    for check_from in check_to_run["from"]:
        result = "No Match"
        for check_against in check_to_run["against"]:
            if check_from["name"] == check_against["name"]:
                result = "Match"
        print("result for item {} from {} compared to items in {}: {}".format(check_from["name"],
                                                                              check_to_run["from_name"],
                                                                              check_to_run["against_name"],
                                                                              result))