Skip to content

Instantly share code, notes, and snippets.

@afr-dt
Created January 18, 2021 07:14
Show Gist options
  • Save afr-dt/d8309976847555424167767b516b3fa3 to your computer and use it in GitHub Desktop.
Save afr-dt/d8309976847555424167767b516b3fa3 to your computer and use it in GitHub Desktop.
Clean empty or None values from dict
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