python - Using the `==` operator on circularly defined dictionaries -


python allows dictionaries compared ==

import copy  child = {'name': 'child'} parent_1 = {'name': 'parent', 'child': child} parent_2 = copy.deepcopy(parent_1) print(parent_1 == parent_2) 

prints true, expect to.

python allows dictionaries reference each other circularly.

child = {'name': 'child'} parent_1 = {'name': 'parent', 'child': child} child['parent'] = parent_1  # create circular reference 

however, trying use == operator on dictionaries circular references raises error.

parent_2 = copy.deepcopy(parent_1) print(parent_1 == parent_2) 

returns

c:\python34\python.exe -i c:/users/anon/.pycharm40/config/scratches/scratch_5 traceback (most recent call last):   file "c:/users/anon/.pycharm40/config/scratches/scratch_5", line 11, in <module>     print(parent_1 == parent_2) runtimeerror: maximum recursion depth exceeded in comparison 

how can check 2 dictionaries circular references equality?

you need define mean equal. "equal" dictionaries means 'all key/value pairs "equal"'. if dictionary has reference itself, definition of equal may lead recursive definition, i.e. a == b iff a == b.

take simple example:

a = {}; a['item'] = b = {}; b['item'] = b 

are a , b equal? in order know that, need first know if a , b equal ...

you create special equal looks this:

def equal(a, b, special=[]):     if not isinstance(a, dict) or not isinstance(b, dict):         return == b      special = special + [a, b]     set_keys = set(a.keys())     if set_keys != set(b.keys()):         return false      key in set_keys:         if any(a[key] in special):             continue         elif any(b[key] in special):             continue         elif not equal(a[key], b[key], special):             return false     return true 

Comments