Created
March 29, 2020 05:02
-
-
Save JakeTheCorn/a33a7326ef10b95b5fa2a93ee764f01d to your computer and use it in GitHub Desktop.
nullifies empty sub dicts
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
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