首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >比较python字典并找出两者的区别

比较python字典并找出两者的区别
EN

Stack Overflow用户
提问于 2014-01-23 00:32:41
回答 2查看 6.2K关注 0票数 0

因此,我试图编写一个包含2个.json文件的python程序,比较它们的内容,并显示两者之间的差异。到目前为止,我的程序使用用户输入来选择两个文件,并对这两个文件进行比较。我试图弄清楚如何打印出这两个文件之间的实际差异。

我的节目:

代码语言:javascript
复制
#!/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示例:

代码语言:javascript
复制
{
    "menu": {
        "popup": {
            "menuitem": [
                {
                    "onclick": "CreateNewDoc()",
                    "value": "New"
                },
                {
                    "onclick": "OpenDoc()",
                    "value": "Open"
                },
                {
                    "onclick": "CloseDoc()",
                    "value": "Close"
                }
            ]
        },
        "id": "file",
        "value": "File"
    }
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-01-23 00:40:54

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

代码语言:javascript
复制
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'

如果要打印实际差异:

代码语言:javascript
复制
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"
票数 3
EN

Stack Overflow用户

发布于 2017-10-23 13:28:26

您可能想尝试一下python中的jsondiff库。https://pypi.python.org/pypi/jsondiff/0.1.0

从网站引用的例子如下。

代码语言:javascript
复制
>>> from jsondiff import diff

>>> diff({'a': 1}, {'a': 1, 'b': 2})
{<insert>: {'b': 2}}

>>> diff({'a': 1, 'b': 3}, {'a': 1, 'b': 2})
{<update>: {'b': 2}}

>>> diff({'a': 1, 'b': 3}, {'a': 1})
{<delete>: ['b']}

>>> diff(['a', 'b', 'c'], ['a', 'b', 'c', 'd'])
{<insert>: [(3, 'd')]}

>>> diff(['a', 'b', 'c'], ['a', 'c'])
{<delete>: [1]}

# Similar items get patched
>>> diff(['a', {'x': 3}, 'c'], ['a', {'x': 3, 'y': 4}, 'c'])
{<update>: [(1, {<insert>: {'y': 4}})]}

# Special handling of sets
>>> diff({'a', 'b', 'c'}, {'a', 'c', 'd'})
{<add>: set(['d']), <discard>: set(['b'])}

# Parse and dump JSON
>>> print diff('["a", "b", "c"]', '["a", "c", "d"]', parse=True, dump=True, indent=2)
{
  "$delete": [
    1
  ],
  "$insert": [
    [
      2,
      "d"
    ]
  ]
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/21297044

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档