【问题标题】:Dictionary recursive compare program字典递归比较程序
【发布时间】:2014-01-29 06:08:40
【问题描述】:

我创建了一个程序来比较两个 python 字典并输出两者的差异。它适用于深度为 2 或更小的字典。我应该怎么做才能处理更深入的字典,还有嵌套的字典?

我遇到的另一个问题是,当我通过 get_json() 函数传递一个 json 数组时,它会以列表形式返回。并且该程序正在使用列表而不是字典进行窃听。我应该如何解决这个问题?

我的程序:

#!/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()

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;"
        }
    }
}

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;"
        }
    }
}

示例输出:

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

【问题讨论】:

    标签: python dictionary


    【解决方案1】:

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

    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)
    

    输出::

    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
    

    请注意,在您的问题中,您没有考虑 key 是否存在差异,因此不会打印 key 的路径。我在我的代码中打印它。我已经从小部件-> 文本中删除了数据元素以进行测试。所以,请忽略这个控制台输出

    【讨论】:

      【解决方案2】:

      无需阅读所有内容,

      def check_dict(first, second):
          for key in first:
              for keyTwo in second:
      
                  if type(first[key]) == dict and type(second[keyTwo]) == dict:
                      return check_dict(first[key], second[keyTwo])
                  if not first[key] == second[keyTwo]:
                      return false
      

      目前无法访问 python 解释器,但类似的东西应该可以工作。这只是一个想法的开始,但希望这是足够的信息来激发一些东西。

      【讨论】:

        猜你喜欢
        • 2017-02-16
        • 2015-10-25
        • 1970-01-01
        • 1970-01-01
        • 2012-02-03
        • 2014-02-16
        • 2016-10-22
        • 2020-12-17
        • 1970-01-01
        相关资源
        最近更新 更多