Skip to content

Instantly share code, notes, and snippets.

@JakeTheCorn
Created March 29, 2020 05:02
Show Gist options
  • Save JakeTheCorn/a33a7326ef10b95b5fa2a93ee764f01d to your computer and use it in GitHub Desktop.
Save JakeTheCorn/a33a7326ef10b95b5fa2a93ee764f01d to your computer and use it in GitHub Desktop.
nullifies empty sub dicts
import unittest
def nullify(v: dict) -> dict or None:
if not isinstance(v, dict):
return v
if not bool(v):
return None
d = {}
for key in v.copy():
d[key] = nullify(v[key])
if d[key] == None:
del d[key]
if not bool(d):
return None
return d
class Test(unittest.TestCase):
def test(self):
tables = [
(None, None),
({}, None),
({'name': 'bob'}, {'name': 'bob'}),
({'m': {}, 'n': {'f': 'b'}}, {'n': {'f': 'b'}}),
({'a': {'a0': {}}}, None)
]
for arg, expectation in tables:
result = nullify(arg)
self.assertEqual(result, expectation)
if __name__ == '__main__':
unittest.main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment