0

I have 2 dictionaries and i am looking to compare them. I want to print total number of differences.

Following program works perfectly to report all differences, how should i modify it to just return total count.

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

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)

current output:

comparing d1 to d2:
a->b :
 -  cs  :  10
 +  cs  :  30
None

Expected output:

comparing d1 to d2:
no of differences: 1
Saurabh Shrivastava
  • 1,394
  • 4
  • 21
  • 50
  • If I understand your question correctly, you don't need a special method for this. The default `==` overload for dicts should just work. – Ammar Askar Sep 07 '19 at 05:43
  • updated my question, i want total count of mismatchs. @AmmarAskar – Saurabh Shrivastava Sep 07 '19 at 06:00
  • Why can't you just use the code you showed, and increment a difference counter in each place where it prints a difference? – joanis Sep 08 '19 at 17:18
  • @joanis : you mean, using a global counter. Local counter would not work, since it is recursive call. I am avoiding global counter since function may be called simultaneously from different sources. – Saurabh Shrivastava Sep 09 '19 at 05:21
  • A local counter will do: findDiff can return the sum of the recursive calls plus the locally counted instances. – joanis Sep 09 '19 at 13:52

0 Answers0