Search code examples
pythonjsondictionarynonetype

Replace None in a python dictionary


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?


Solution

  • 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)