词典递归比较程序 [英] Dictionary recursive compare program

查看:105
本文介绍了词典递归比较程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个程序,比较两个python字典并输出两者的差异。它与一个深度为2或更小的dict的工作。我能做些什么来处理更深层次的死者,也是嵌套的人?



我遇到的另一个问题是当我通过我的get_json()函数传递一个json数组,它返回一个列表。该程序正在使用列表而不是一个dict。我应该如何解决这个问题?



我的程序:

 #!/ usr / bin / env python2 

进口JSON

DEF get_json():
FILE_NAME =的raw_input( 输入JSON文件的名称:)与开放(FILE_NAME)
作为json_file:
json_data = json.load(json_file)
返回json_data

DEF print_diff(json1,json2):
。在json1 N:
如果n不在json2中:
print(' - '+ str(n)+':')
在json2中为n:
如果n不在json1中:
print('+'+ str(n)+':')
continue
如果json2 [n]!= json1 [n]:
如果type(json2 [n]不是(dict,list):
print(' - ''+ str(n)+':'+ str(json1 [n]))
print('+'+ (n)+':'+ str(json2 [n]))
else:
如果type(json2 [n])== dict:
print_diff(json1 [n] ,json2 [n])
继续
返回


DEF的main():
文件1 = get_json()
打印(类型(文件1))
文件2 = get_json ()
打印(类型(文件2))
print_diff(文件1,文件2)

如果__name__ == __main__:
的main()

dict 1的示例:

 widget:{
debug:on,
window:{
title:Sample Konfabulator Widget b $ bname:main_window,
width:500,
height:500
},
image:{
src:Images / Sun.png,
name:sun1,
hOffset:250,
vOffset:250,
alignment :中心
},
text:{
data:点击此处,
size:36,
style bold,
name:text1,
hOffset:2 50,
vOffset:100,
alignment:center,
onMouseUp:sun1.opacity =(sun1.opacity / 100)* 90;
}
}
}

dict 2的示例: / p>

  {
widget:{
debug:on,
窗口:{
title:Sample Konfabulator Widget,
name:main_window,
width:500,
height b $ b},
image:{
src:Images / Sun.png,
name:sun2,
hOffset 100,
vOffset:100,
alignment:center
},
text:{
data:点击此处 ,
size:36,
style:bold,
name:text1,
hOffset:250,
vOffset:100,
alignment:center,
onMouseUp:sun1.opacity =(sun1.opacity / 100)* 90;
}
}
}

示例输出:

 输入JSON文件的名称:JSON1.json 
< type'dict'>
输入JSON文件的名称:JSON2.json
< type'dict'>
- vOffset:250
+vOffset:100
- name:sun1
+name:sun2
- hOffset:250
+hOffset:100


解决方案

我写了以下代码,可以比较不同深度的两个字典,并将差异打印到控制台输出。请注意,如果在第一个字典中找到密钥,而在第二个字典中找不到,则只会打印没有找到的密钥(它不会在趴树下打印)。我希望这是预期的。此代码适用于单向比较,因此您需要进行两次调用以比较字典。

  def findDiff(d1 ,d2,path =):
d1.keys()中的k:
如果不是d2.has_key(k):
打印路径,:
打印k +作为键不在d2,\\\

else:
如果type(d1 [k])是dict:
如果path ==:
path = k
else:
path = path + - > + k
findDiff(d1 [k],d2 [k],path)
else:
如果d1 [k]!= d2 [k]:
打印路径, :
print - ,k,:,d1 [k]
print+,k,:,d2 [k]

print将s1与s2进行比较:
print findDiff(s1,s2)
print将s2与s1进行比较:
print findDiff(s2,s1)

输出::

 将s1与s2进行比较:
widget-> text:
数据作为键不在d2
widget-> text-> window-> image:
- vOffset:250
+ vOffset:100
widget-> text-> window-> image:
- 名称:sun1
+名称:sun2
widget-> text-> ; window-> image:
- hOffset:250
+ hOffset:100

将s2与s1进行比较:
widget-> text->窗口 - > image:
- vOffset:100
+ vOffset:250
widget-> text-> window-> image:
- name: sun2
+名称:sun1
widget-> text-> window-> image:
- hOffset:100
+ hOffset:250

请注意,在您的问题中,您没有考虑密钥,密钥路径是否有差异未打印。我正在我的代码中打印。我从widget->文本中删除了数据元素进行测试。所以,请忽略这个控制台输出


I created a program that compares two python dictionaries and outputs the differences of the two. It works with a dict that has a depth of 2 or less. What should I do to be able to handle dicts with more depth, also nested dicts?

Another problem that I am having is when I pass a json array through my get_json() function it returns as a list. And the program is bugging out with the list instead of a dict. How should i go about solving that?

My program:

#!/usr/bin/env python2

import json

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

def print_diff(json1, json2):
    for n in json1:
        if n not in json2:
            print('-   "' + str(n) + '":')
    for n in json2:
        if n not in json1:
            print('+   "' + str(n) + '":')
            continue
        if json2[n] != json1[n]:
            if type(json2[n]) not in (dict, list):
                print('-   "' + str(n) + '" : "' + str(json1[n]))
                print('+   "' + str(n) + '" : "' + str(json2[n]))
            else:
                if type(json2[n]) == dict:
                    print_diff(json1[n], json2[n])
                    continue
    return


def main():
    file1 = get_json()
    print(type(file1))
    file2 = get_json()
    print(type(file2))
    print_diff(file1, file2)

if __name__ == "__main__":
    main()

example of dict 1:

{
    "widget": {
        "debug": "on",
        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "width": 500,
            "height": 500
        },
        "image": {
            "src": "Images/Sun.png",
            "name": "sun1",
            "hOffset": 250,
            "vOffset": 250,
            "alignment": "center"
        },
        "text": {
            "data": "Click Here",
            "size": 36,
            "style": "bold",
            "name": "text1",
            "hOffset": 250,
            "vOffset": 100,
            "alignment": "center",
            "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
        }
    }
}

example of dict 2:

{
    "widget": {
        "debug": "on",
        "window": {
            "title": "Sample Konfabulator Widget",
            "name": "main_window",
            "width": 500,
            "height": 500
        },
        "image": {
            "src": "Images/Sun.png",
            "name": "sun2",
            "hOffset": 100,
            "vOffset": 100,
            "alignment": "center"
        },
        "text": {
            "data": "Click Here",
            "size": 36,
            "style": "bold",
            "name": "text1",
            "hOffset": 250,
            "vOffset": 100,
            "alignment": "center",
            "onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
        }
    }
}

example output:

Enter name of JSON File: JSON1.json
<type 'dict'>
Enter name of JSON File: JSON2.json
<type 'dict'>
-   "vOffset" : "250
+   "vOffset" : "100
-   "name" : "sun1
+   "name" : "sun2
-   "hOffset" : "250
+   "hOffset" : "100

解决方案

I have written following code which can compare two dictionaries with different depths and print the differences to console output. Please note that, if the key is found in first dictionary and not found in second, it would just print only not found key (it will not print under lying tree). I hope this is what expected. This code works for one way comparison, so you need to make two calls for comparing dictionary in other way.

def findDiff(d1, d2, path=""):
    for k in d1.keys():
        if not d2.has_key(k):
            print path, ":"
            print k + " as key not in d2", "\n"
        else:
            if type(d1[k]) is dict:
                if path == "":
                    path = k
                else:
                    path = path + "->" + k
                findDiff(d1[k],d2[k], path)
            else:
                if d1[k] != d2[k]:
                    print path, ":"
                    print " - ", k," : ", d1[k]
                    print " + ", k," : ", d2[k] 

print "comparing s1 to s2:"
print findDiff(s1,s2)
print "comparing s2 to s1:"
print findDiff(s2,s1)

Output::

comparing s1 to s2:
widget->text :
data as key not in d2 
widget->text->window->image :
 -  vOffset  :  250
 +  vOffset  :  100
widget->text->window->image :
 -  name  :  sun1
 +  name  :  sun2
widget->text->window->image :
 -  hOffset  :  250
 +  hOffset  :  100
None
comparing s2 to s1:
widget->text->window->image :
 -  vOffset  :  100
 +  vOffset  :  250
widget->text->window->image :
 -  name  :  sun2
 +  name  :  sun1
widget->text->window->image :
 -  hOffset  :  100
 +  hOffset  :  250
None

Please note that, in your question you have not considered if there is a difference in key , path of the key is not printed. I am printing it in my code. I have deleted data element from widget->text for testing. so, pls ignore this console output

这篇关于词典递归比较程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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