Last active
December 17, 2015 04:58
-
-
Save lawliet89/5554157 to your computer and use it in GitHub Desktop.
Strip list/dictionaries of empty items recursively
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 strip(content): | |
"""Strip Empty Variables""" | |
if (type(content) is list): | |
return strip_list(content) | |
elif (type(content) is dict): | |
return strip_dictionary(content) | |
elif (content): | |
return content | |
else: | |
return None | |
def strip_dictionary(dictionary): | |
"""Recursively strip a dictionary of empty items or string""" | |
if (type(dictionary) is list): | |
return strip_list(dictionary) | |
# recursively strip | |
dictionary = { k: strip(v) for k, v in dictionary.iteritems()} | |
# strip empty items | |
return { k: v for k, v in dictionary.iteritems() if v} | |
def strip_list(lst): | |
"""Recursively strip a list of empty items or string""" | |
if (type(lst) is dict): | |
return strip_dictionary(lst) | |
# recursively strip list | |
lst = map(strip, lst) | |
# remove empty items | |
return [v for v in lst if v] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment