Skip to content

Instantly share code, notes, and snippets.

@rbonvall
Last active December 25, 2015 00:19
Show Gist options
  • Save rbonvall/6886837 to your computer and use it in GitHub Desktop.
Save rbonvall/6886837 to your computer and use it in GitHub Desktop.
Helper functions for debugging deeply nested data structures on the console.
def dictcompare(da, db):
ka = set(da.keys())
kb = set(db.keys())
if ka & kb:
if ka - kb:
print 'Keys only in A:', ka - kb
if kb - ka:
print 'Keys only in B:', kb - ka
else:
print 'No keys in common'
differing_keys = [k for k in ka & kb if da[k] != db[k]]
if differing_keys:
print 'Keys with different values:', ', '.join(differing_keys)
def listcompare(la, lb):
na = len(la)
nb = len(lb)
if na != nb:
print 'Lists have different lengths'
differing_indices = [i for i, (xa, xb) in enumerate(zip(la, lb)) if xa != xb]
if differing_indices:
print 'Indices with different values:', ', '.join(map(str, differing_indices))
def compare(a, b):
if isinstance(a, list) and isinstance(b, list):
listcompare(a, b)
elif isinstance(a, dict) and isinstance(b, dict):
dictcompare(a, b)
elif type(a) != type(b):
print 'Values have different types ({0} and {1})'.format(type(a), type(b))
elif a != b:
print 'a == {0}, b == {1}'.format(repr(a), repr(b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment