Created
January 18, 2021 07:14
-
-
Save afr-dt/d8309976847555424167767b516b3fa3 to your computer and use it in GitHub Desktop.
Clean empty or None values from dict
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
def clean_empty_or_none(d): | |
""" | |
Clean empty or None values from dict | |
""" | |
clean = {} | |
for k, v in d.items(): | |
if isinstance(v, dict): | |
nested = clean_empty_or_none(v) | |
if len(nested.keys()) > 0: | |
clean[k] = nested | |
elif v and v is not None: | |
clean[k] = v | |
return clean | |
data = { | |
"first_name": "Jon", | |
"middle_name": None, | |
"last_name": "", | |
"family": { | |
"mother": "Sophie", | |
"father": "Pepe", | |
"brother": "", | |
"sister": None | |
} | |
} | |
print(clean_empty_or_none(data)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment