比较python字典并找出两者的差异 [英] Comparing python dictionaries and find diffrence of the two

查看:416
本文介绍了比较python字典并找出两者的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我试图编写一个将使用2个.json文件的python程序,将内容进行比较并显示两者之间的差异.到目前为止,我的程序需要用户输入才能选择两个文件,然后将两个文件进行比较就可以了.我碰到了一堵墙,试图弄清楚如何打印两个文件之间的实际差异.

So im trying to write a python program that will take 2 .json files compare the contents and display the differences between the two. So far my program takes user input to select two files and compares the two just fine. I have hit a wall trying to figure out how to print what the actual differences are between the two files.

我的程序:

#!/usr/bin/env python2

import json

#get_json() requests user input to select a .json file
#and creates a python dict with the information
def get_json():
    file_name = raw_input("Enter name of JSON File: ")
    with open(file_name) as json_file:
        json_data = json.load(json_file)
        return json_data

#compare_json(x,y) takes 2 dicts, and compairs the contents
#print match if equal, or not a match if there is difrences
def compare_json(x,y):
    for x_values, y_values in zip(x.iteritems(), y.iteritems()):
        if x_values == y_values:
            print 'Match'
        else:
            print 'Not a match'

def main():
    json1 = get_json()
    json2 = get_json()
    compare_json(json1, json2)

if __name__ == "__main__":
    main()

我的.json示例:

{
    "menu": {
        "popup": {
            "menuitem": [
                {
                    "onclick": "CreateNewDoc()",
                    "value": "New"
                },
                {
                    "onclick": "OpenDoc()",
                    "value": "Open"
                },
                {
                    "onclick": "CloseDoc()",
                    "value": "Close"
                }
            ]
        },
        "id": "file",
        "value": "File"
    }
}

推荐答案

您的问题源于以下事实:字典存储在具有内部逻辑一致性的结构中-当您请求someDict.items()someOtherDict.items()时,密钥元素的-值"对通过相同算法计算.但是,由于可能存在于任一词典中的键的差异,因此相同的键可能不会出现在由调用dict.items()返回的任一列表中的相应索引中.因此,最好检查另一个字典中是否存在特定键,并比较两者中的关联值.

Your problem stems from the fact that dictionaries are stored in a structure with an internal logical consistency - when you ask for someDict.items() and someOtherDict.items(), the key-value pairs of elements are computed by the same algorithm. However, due to differences in the keys that may be present in either dictionary, identical keys may not be present in the corresponding index in either list returned by the call to dict.items(). As a result, you are much better off checking if a particular key exists in another dictionary, and comparing the associated value in both.

def compare_json(x,y):
    for x_key in x:
        if x_key in y and x[x_key] == y[x_key]:
            print 'Match'
        else:
            print 'Not a match'
    if any(k not in x for k in y):
        print 'Not a match'

如果要打印出实际差异:

If you want to print out the actual differences:

def printDiffs(x,y):
    diff = False
    for x_key in x:
        if x_key not in y:
            diff = True
            print "key %s in x, but not in y" %x_key
        elif x[x_key] != y[x_key]:
            diff = True
            print "key %s in x and in y, but values differ (%s in x and %s in y)" %(x_key, x[x_key], y[x_key])
    if not diff:
        print "both files are identical"

这篇关于比较python字典并找出两者的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆