-
-
Save alecklandgraf/5fa9124318549113ce0e to your computer and use it in GitHub Desktop.
Display values from a deeply nested dict in python
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 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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage: