I happen to have a complex dictionary (having lists, dicts within lists etc). The values for some of the keys are set as None
Is there a way I can replace this None with some default value of my own irrespective of the complex structure of the dictionary?
items () method is used to return the list with all dictionary keys with values. We will be using a for loop to check if a value from the dictionary d matches with None. If the condition is true, then we simply delete the key that has None as its value. Here is the complete Python code to remove None values from a dictionary:
Given a dictionary, replace None values in every nesting with an empty dictionary. Explanation : All None values are replaced by empty dictionaries. Explanation : All None values are replaced by empty dictionaries. In this, we check for dictionary instance using isinstance () and call for recursion for nested dictionary replacements.
Explanation : All None values are replaced by empty dictionaries. Explanation : All None values are replaced by empty dictionaries. In this, we check for dictionary instance using isinstance () and call for recursion for nested dictionary replacements.
items () method is used to return the list with all dictionary keys with values. We will be using a for loop to check if a value from the dictionary d matches with None.
You can do it using object_pairs_hook
from json
module:
def dict_clean(items):
result = {}
for key, value in items:
if value is None:
value = 'default'
result[key] = value
return result
dict_str = json.dumps(my_dict)
my_dict = json.loads(dict_str, object_pairs_hook=dict_clean)
# replace_none_with_empty_str_in_dict.py
raw = {'place': 'coffee shop', 'time': 'noon', 'day': None}
def replace_none_with_empty_str(some_dict):
return { k: ('' if v is None else v) for k, v in some_dict.items() }
print(replace_none_with_empty_str(raw))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With