Skip to content

Instantly share code, notes, and snippets.

@lawliet89
Last active December 17, 2015 04:58
Show Gist options
  • Save lawliet89/5554157 to your computer and use it in GitHub Desktop.
Save lawliet89/5554157 to your computer and use it in GitHub Desktop.
Strip list/dictionaries of empty items recursively
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