Skip to content

Instantly share code, notes, and snippets.

@ekiro
Last active December 16, 2015 10:49
Show Gist options
  • Save ekiro/5422659 to your computer and use it in GitHub Desktop.
Save ekiro/5422659 to your computer and use it in GitHub Desktop.
Recursively removes empty elements (list, dicts, strings)
import numbers
def remove_empty_nodes(struct):
"""
In: [1, 2, [], 0, {'a': 'b', 'c': '', 'd': {'1': []}}, [1, [2, [[], []]]]]
Out: [1, 2, 0, {'a': 'b'}, [1, [2]]]
"""
def keep(v):
return isinstance(v, numbers.Number) or v
if type(struct) == list:
struct = [remove_empty_nodes(s) for s in struct]
struct = filter(keep, struct)
if type(struct) == dict:
for k, v in struct.iteritems():
struct[k] = remove_empty_nodes(v)
struct = dict(
(
(k, v) for k, v in struct.iteritems()
if keep(v)
)
)
return struct
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment