Last active
September 27, 2022 17:59
-
-
Save NucciTheBoss/bac663616950ec9ee0a58e4dae8f3163 to your computer and use it in GitHub Desktop.
Filtering a dictionary recursively
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
#!/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