Home > Software design >  replace all empty string values in a dictionary with null in python
replace all empty string values in a dictionary with null in python

Time:10-19

how to replace all empty string values in a dictionary like bellow with null.

values can be dictionary, too.


test_dict = {
    'hi': {'h': '', 'i': 'i'},
    'bye': {},
    'sth': ''
}

CodePudding user response:

The following recursive function will do:

def to_null(obj):
    if obj != "":
        if isinstance(obj, dict):
            return {k: to_null(v) for k, v in obj.items()}
        return obj

to_null(test_dict)
# {'hi': {'h': None, 'i': 'i'}, 'bye': {}, 'sth': None}

CodePudding user response:

def empty_str_value_to_none(parent_dict, key=None):
    if key is not None:
        value = parent_dict[key]
    else:
        value = parent_dict

    if type(value) == dict:
        for sub_key in value:
            empty_str_value_to_none(value, sub_key)
    elif value == "":
        parent_dict[key] = None


empty_str_value_to_none(test_dict)
print(test_dict)
  • Related