Skip to content

Instantly share code, notes, and snippets.

@m1el
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save m1el/9089935 to your computer and use it in GitHub Desktop.
Save m1el/9089935 to your computer and use it in GitHub Desktop.
recursive dict comparison with self-reference
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