Skip to content

Instantly share code, notes, and snippets.

@NucciTheBoss
Last active September 27, 2022 17:59
Show Gist options
  • Save NucciTheBoss/bac663616950ec9ee0a58e4dae8f3163 to your computer and use it in GitHub Desktop.
Save NucciTheBoss/bac663616950ec9ee0a58e4dae8f3163 to your computer and use it in GitHub Desktop.
Filtering a dictionary recursively
#!/usr/bin/env python3
"""Filter None out of a dictionary with nested data structures."""
from typing import Dict
def filterdict(dirty: Dict) -> Dict:
"""Filter `None` values out of a dictionary.
Args:
dirty (Dict): Dictionary with None values present.
Returns:
Dict: Dictionary with None values removed.
"""
clean = {}
for k, v in dirty.items():
if v is not None:
if isinstance(v, dict):
clean.update({k: filterdict(v)})
elif isinstance(v, list):
placeholder = []
for i in v:
if i is not None:
if isinstance(i, dict):
placeholder.append(filterdict(i))
else:
placeholder.append(i)
clean.update({k: placeholder})
else:
clean.update({k: v})
return clean
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment