Python: a tool for comparing dict pairs of varying depths?

I have a couple of pairs of fairly large dictons. The structure of the dicts pair is exactly the same, but the values ​​will be different. All pairs differ in how much they are nested.

To clarify:

  • dict_a has the same structure as dict_b
  • dict_chas the same structure as dict_d(but differs from dict_a and dict_b)

etc..

Is there a tool that simplifies the implementation of a function for comparing only values and / or does some basic arithmetic? My dicts can be pretty nested, so simple [for k,v in dict_x.iteritems()...]won't.

+4
source share
1 answer

... !

, , . dict_a dict_b, : . , , .

def dict_compare(da, db):
    for k, v in da.iteritems():
        if isinstance(v, dict): #if the value is another dict:
            dict_compare(v, db[k]) #enter into the comparison function again!
        else:
            if v != db[k]: 
                print 'values not equal at', k

dict_compare(dict_a, dict_b)

, , .

, - , , , , if v != db[k].

0

Source: https://habr.com/ru/post/1525781/


All Articles