Skip to content

Instantly share code, notes, and snippets.

@alecklandgraf
Forked from anonymous/file1.py
Last active February 10, 2016 00:37
Show Gist options
  • Save alecklandgraf/5fa9124318549113ce0e to your computer and use it in GitHub Desktop.
Save alecklandgraf/5fa9124318549113ce0e to your computer and use it in GitHub Desktop.
Display values from a deeply nested dict in python
def dicty(d, key=None):
"""removes empty string and None values from a nested dict, if key, then prints all values within the dict"""
if key:
for k, v in d.items():
if k.lower() == key.lower():
print "{}: {}".format(k, v)
if isinstance(v, dict):
dicty(v, key)
if isinstance(v, list):
for x in v:
if isinstance(x, dict):
dicty(x, key)
else:
temp_d = {}
for k, v in d.items():
if v is None or (isinstance(v, basestring) and not v.strip()):
continue
elif isinstance(v, dict):
temp_nested_d = dicty(v)
if temp_nested_d:
temp_d[k] = temp_nested_d
else:
temp_d[k] = v
return temp_d
@alecklandgraf
Copy link
Author

Usage:

>>> d = {'a': 0, 'b': {'hello': None}, 'c': ['a', {'d': None, 'stage': 'IN_PROGRESS'}, {'stage': 'DONE'}]}
>>> dicty(d)
{'a': 0, 'c': ['a', {'d': None, 'e': 0}, {'e': 1}]}
>>> dicty(d, 'stage')
stage: IN_PROGRESS
stage: DONE

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment