Replace None in a python dictionary

MSK picture MSK · Mar 14, 2016 · Viewed 21.7k times · Source

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?

Answer

Eugene Soldatov picture Eugene Soldatov · Mar 14, 2016

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)