Last active
August 29, 2015 13:56
-
-
Save m1el/9089935 to your computer and use it in GitHub Desktop.
recursive dict comparison with self-reference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def dictcmp(a, b, stacka=None, stackb=None): | |
if a is b: | |
return True | |
if type(a) is not type(b): | |
return False | |
stacka = stacka or [] | |
stackb = stackb or [] | |
stacka.append(id(a)) | |
stackb.append(id(b)) | |
res = False | |
if isinstance(a, (list, dict)): | |
ia = stacka.index(id(a)) | |
ib = stackb.index(id(b)) | |
if ia != ib: | |
res = False | |
elif ia < len(stacka) - 1: | |
res = True # already comparing these | |
else: | |
if isinstance(a, list): | |
res = all(dictcmp(ia, ib, stacka, stackb) for ia, ib in zip(a, b)) | |
elif isinstance(a, dict): | |
ka = a.keys() | |
if ka != b.keys(): | |
res = False | |
else: | |
res = all(dictcmp(a[k], b[k], stacka, stackb) for k in ka) | |
else: | |
res = a == b | |
stacka.pop() | |
stackb.pop() | |
return res |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment