Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 787
MSK Avatar asked Mar 14 '16 11:03

MSK


People also ask

How to remove None values from a dictionary in Python?

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:

How to replace None values in every nesting with an empty 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.

Which dictionary will be replaced by 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.

How to return list with all dictionary keys with values in Python?

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.


2 Answers

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)
like image 176
Eugene Soldatov Avatar answered Sep 29 '22 21:09

Eugene Soldatov


# 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))
like image 21
Down the Stream Avatar answered Sep 29 '22 22:09

Down the Stream