Skip to content

Instantly share code, notes, and snippets.

@dsaad68
Created September 3, 2023 18:24
Show Gist options
  • Save dsaad68/e72930fe6381eb27b835d646b83802bd to your computer and use it in GitHub Desktop.
Save dsaad68/e72930fe6381eb27b835d646b83802bd to your computer and use it in GitHub Desktop.
Nested dictionary None Rremover
def dict_none_remover(d:dict) -> dict:
"""
Remove keys with None values from a multi-level nested dictionary.
Parameters
----------
d : dict
The input dictionary from which keys with None values should be removed.
Returns
-------
dict or None
A new dictionary with keys having None values removed.
Raises
------
TypeError
If the input is not a dictionary.
Examples
--------
>>> remove_none_values({'a': 1, 'b': None, 'c': {'d': 2, 'e': None}})
{'a': 1, 'c': {'d': 2}}
"""
try:
if not isinstance(d, dict):
raise TypeError("Input must be of type dict")
new_dict = {}
for key, value in d.items():
if isinstance(value, dict):
value = dict_none_remover(value)
if value is not None:
new_dict[key] = value
return new_dict
except TypeError as e:
print(f"Error: {e}")
def none_remover(data):
"""
Recursively remove None values from a dictionary or list.
Parameters
----------
data: dict or list
The dictionary or list from which to remove None values.
Returns:
dict or list:
A new dictionary or list with all None values removed.
The structure of the input (dict or list) is maintained.
"""
try:
if isinstance(data, dict):
new_dict = {}
for key, value in data.items():
if value is not None:
if isinstance(value, (dict, list)):
value = none_remover(value)
new_dict[key] = value
return new_dict
elif isinstance(data, list):
new_list = []
for value in data:
if value is not None:
if isinstance(value, (dict, list)):
value = none_remover(value)
new_list.append(value)
return new_list
else:
data # You might want to explicitly return the value here
except Exception as e:
print(f"An error occurred: {e}")
def test_none_remover():
# Normal Dictionary
assert none_remover({'a': 1, 'b': None}) == {'a': 1}
# Double Nested Dictionary
assert none_remover({'a': 1, 'b': None, 'c': {'d': 2, 'e': None}}) == {'a': 1, 'c': {'d': 2}}
# Triple Nested Dictionary
assert none_remover({'a': 1, 'b': None,'c': {'d': 2, 'e': None ,'f': {'g': 1, 'h': None}}}) == {'a': 1, 'c': {'d': 2, 'f': {'g': 1}}}
# Double Nested Dictionary with List
assert none_remover({'a': 1, 'b': None, 'c': {'d': 2, 'e': None, 'f': [{'g': 1, 'h': None}, {'i': 2, 'j': None}]}}) == {'a': 1, 'c': {'d': 2, 'f': [{'g': 1}, {'i': 2}]}}
# Triple Nested Dictionary with List
assert (
none_remover({'a': 1, 'b': None,'c': {'d': 2, 'e': None ,'f': {'g': 1, 'h': None}, 'i': [{'j': 3, 'k': None}, {'l': 4, 'm': None, 'n': [{'o': 5, 'p': None}]}] }})
== {'a': 1, 'c': {'d': 2, 'f': {'g': 1}, 'i': [{'j': 3}, {'l': 4, 'n': [{'o': 5}]}]}}
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment