两个python字典(键和值)的递归差异 [英] Recursive diff of two python dictionaries (keys and values)

查看:592
本文介绍了两个python字典(键和值)的递归差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一个python字典,称之为 d1 ,并在稍后一段时间将该字典的版本称为 d2 。我想查找 d1 d2 之间的所有更改。换句话说,添加,删除或更改的所有内容。值得注意的是,这些值可以是int,string,list或dicts,因此需要递归。这是我到目前为止:

So I have a python dictionary, call it d1, and a version of that dictionary at a later point in time, call it d2. I want to find all the changes between d1 and d2. In other words, everything that was added, removed or changed. The tricky bit is that the values can be ints, strings, lists, or dicts, so it needs to be recursive. This is what I have so far:

def dd(d1, d2, ctx=""):
    print "Changes in " + ctx
    for k in d1:
        if k not in d2:
            print k + " removed from d2"
    for k in d2:
        if k not in d1:
            print k + " added in d2"
            continue
        if d2[k] != d1[k]:
            if type(d2[k]) not in (dict, list):
                print k + " changed in d2 to " + str(d2[k])
            else:
                if type(d1[k]) != type(d2[k]):
                    print k + " changed to " + str(d2[k])
                    continue
                else:
                    if type(d2[k]) == dict:
                        dd(d1[k], d2[k], k)
                        continue
    print "Done with changes in " + ctx
    return

它的工作原理很好,除非该值是列表。我不能很好地提出一个优雅的方式处理列表,没有一个巨大的,稍微改变的版本的这个功能重复一个 if(type(d2)== list)

It works just fine unless the value is a list. I cant quite come up with an elegant way to deal with lists, without having a huge, slightly changed version of this function repeated after a if(type(d2) == list).

任何想法?

编辑:这不同于这篇文章,因为这些键可以改变

This differs from this post because the keys can change

推荐答案

一个选项是将您作为词典运行的任何列表转换为索引作为关键字。例如:

One option would be to convert any lists you run into as dictionaries with the index as a key. For example:

# add this function to the same module
def list_to_dict(l):
    return dict(zip(map(str, range(len(l))), l))

/ p>

# add this code under the 'if type(d2[k]) == dict' block
                    elif type(d2[k]) == list:
                        dd(list_to_dict(d1[k]), list_to_dict(d2[k]), k)

这是您在评论中给出的示例字典的输出:

Here is the output with the sample dictionaries you gave in comments:

>>> d1 = {"name":"Joe", "Pets":[{"name":"spot", "species":"dog"}]}
>>> d2 = {"name":"Joe", "Pets":[{"name":"spot", "species":"cat"}]}
>>> dd(d1, d2, "base")
Changes in base
Changes in Pets
Changes in 0
species changed in d2 to cat
Done with changes in 0
Done with changes in Pets
Done with changes in base

请注意,将索引按索引进行比较,因此需要进行一些修改才能正常添加或删除列表项。

Note that this will compare index by index, so it will need some modification to work well for list items being added or removed.

这篇关于两个python字典(键和值)的递归差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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