比较Python字典和嵌套字典 [英] Comparing Python dictionaries and nested dictionaries

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

问题描述

我知道有几个类似的问题,但我的问题是相当不同,我很难。
我有两个字典:

I know there are several similar questions out there, but my question is quite different and difficult for me. I have two dictionaries:

d1= {'a':{'b':{'cs':10},'d':{'cs':20}}}
d2= {'a':{'b':{'cs':30} ,'d':{'cs':20}},'newa':{'q':{'cs':50}}}

i.e d1 has key -- a
and d2 has keys -- a,newa
(in other words d1 is my old dict and d2 is my new dict)

以迭代这些字典,如果在d2中找到键a时,如果键是相同的检查其值(嵌套的dict),例如

I want to iterate over these dictionaries such that, if the key is same check for its value(nested dict), e.g

检查是否有b,如果是检查值cs(从10到30变化),如果这个值改变我想打印它。

when I find key "a" in d2, I will check whether there is b, if yes check value of cs (changed from 10 to 30), if this value is changed I want to print it.

另一种情况是,我想从d2中获取键newa作为新添加的键。

Another case is, I want to get key "newa" from d2 as the newly added key.

因此,在迭代这两个dicts后,基本上,我想要o / p如下:

Hence, after iterating through these 2 dicts , basically , I want the o/p to be as following:

Expected Output: 
 "d2" has new key "newa"
 Value of "cs" is changed from 10 to 30 of key "b" which is of key "a"

I有跟随代码与我,我尝试与许多循环,但不工作,但也不是一个好的选择,因此我正在寻找是否我可以得到预期输出与递归代码。

I have the followiing code with me, I am trying with many loops which not working though ,but is not a good option too, hence I am looking to find whether I can get expected output with a recursive piece of code.

for k,v in d1.iteritems():
    for k1,v1 in d2.iteritems():
        if k is k1:
            print k
            for k2 in v:
                for k3 in v1:
                    if k2 is k3:
                        print k2,"sub key matched"

        else:
            print "sorry no match found"


推荐答案

使用递归比较2个字典:

comparing 2 dictionaries using recursion:

d1= {'a':{'b':{'cs':10},'d':{'cs':20}}}
d2= {'a':{'b':{'cs':30} ,'d':{'cs':20}},'newa':{'q':{'cs':50}}}

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 d1 to d2:"
print findDiff(d1,d2)
print "comparing d2 to d1:"
print findDiff(d2,d1)

输出:

comparing d1 to d2:
a->b :
 -  cs  :  10
 +  cs  :  30
None
comparing d2 to d1:
a->b :
 -  cs  :  30
 +  cs  :  10
a :
newa as key not in d2 

None

这篇关于比较Python字典和嵌套字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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