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.

Revisions

  1. afr-dt created this gist Jan 18, 2021.
    29 changes: 29 additions & 0 deletions clean_empty_or_none.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    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))