Python嵌套字典比较算法

标签 python algorithm dictionary nested compare

<分区>

我有一个比较两个 python 字典的程序,对于深度为 1 的非嵌套字典,它工作得很好。算法非常简单:

for key in dict1, if not in dict2
    print "-" key
for key in dict2, if not in dict1
    print "+" key
for dict2Value, if not equal to dict1Value
    print "+" dict2value
    print "-" dict1value

正如我所说,它适用于深度为 1 且未嵌套的字典。我应该如何更改算法以处理更深层次的嵌套和字典,我已经被困了一段时间。

我的代码:

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

最佳答案

以下采用较短的形式输出差异(您可以根据自己的情况进行更改)。

层次结构由输出中的 START/STOP 表示。

>>> def dictdiff(d1, d2):
    s1, s2 = set(d1), set(d2)
    in1, in12, in2 = s1 - s2, s1 & s2, s2 - s1
    if in1:  print('Keys only in 1:', sorted(in1))
    if in2:  print('Keys only in 2:', sorted(in2))
    sameval = {key for key in in12 if d1[key] == d2[key]}
    if sameval: print('Keys with equal values:', sorted(sameval))
    diffval = in12 - sameval
    diffdict = {key for key in diffval if type(d1[key]) == type(d2[key]) == dict}
    diffother = diffval - diffdict
    if diffother: print('Keys with different values (that are not both dicts):', sorted(diffother))
    for key in sorted(diffdict):
        print('## START dictdiff for common key', key)
        dictdiff(d1[key], d2[key])
        print('## STOP  dictdiff for common key', key)


>>> d1 = dict(a=1, b=2, c=dict(x=1, y=2), d=1, f=dict(s=1, t=3))
>>> d2 = dict(a=1, b=3, c=dict(x=1, y=2), e=1, f=dict(s=1, t=2))
>>> dictdiff(d1, d2)
Keys only in 1: ['d']
Keys only in 2: ['e']
Keys with equal values: ['a', 'c']
Keys with different values (that are not both dicts): ['b']
## START dictdiff for common key f
Keys with equal values: ['s']
Keys with different values (that are not both dicts): ['t']
## STOP  dictdiff for common key f
>>> 

最好记住以下几点:

>>> d1['c'] is d2['c']
False
>>> d1['c'] == d2['c']
True
>>> 

关于Python嵌套字典比较算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21567132/

相关文章:

python - 远程控制或脚本打开 Office 从 Python 编辑 Word 文档

algorithm - 常数空间和线性时间平衡括号算法存在吗?

algorithm - OpenStreetMap:获取公园的所有入口

java - 如何创建编码器?解码器?

python - 将 numpy 矩阵相加

python - 获取python多处理池中worker的唯一ID

python - 将 dict 的嵌套列表展平为 Pandas Dataframe

c# - 在不同的String字典上做benchmark,普通的比较快,不知道为什么

postgresql - Psycopg2 在 postgres 数据库中插入 python 字典

python - HTTP 错误 403 : Forbidden when using NLTK