Last active
December 16, 2015 10:49
-
-
Save ekiro/5422659 to your computer and use it in GitHub Desktop.
Recursively removes empty elements (list, dicts, strings)
This file contains hidden or 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
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