Skip to content

Instantly share code, notes, and snippets.

@ruizjme
Created November 6, 2018 03:39
Show Gist options
  • Save ruizjme/ede300cbfadf998296ee56d4751e016a to your computer and use it in GitHub Desktop.
Save ruizjme/ede300cbfadf998296ee56d4751e016a to your computer and use it in GitHub Desktop.
transverse python dict
def transverse_dict(d, indent=0, level=None, abstract=False):
"""Transverse dictionary to see underlying structure
indent: amount of indent when outputing to console
level: max depth when transversing
abstract: if True, prints the datatype for items
that are not lists or dicts.
if False, prints the items themselves
"""
if level is not None:
level -= 1
if level == -1:
return
if isinstance(d, dict):
for k,v in d.items():
print(' '*indent,k)
transverse_dict(v, indent=indent+4, level=level, abstract=abstract)
elif isinstance(d, list):
for i in d:
transverse_dict(i, indent=indent+4, level=level, abstract=abstract)
else:
if abstract:
print(' '*indent, str(type(d)).split("'")[1])
else:
print(' '*indent, d)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment