简体   繁体   English

在 python 字典中替换 None

[英]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某些键的值设置为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?有没有办法可以用我自己的一些默认值替换这个None而不考虑字典的复杂结构?

You can do it using object_pairs_hook from json module:您可以使用json模块中的object_pairs_hook来做到这一点:

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

Recursive solution from Lutz: Lutz的递归解决方案:

def replace(any_dict):
    for k, v in any_dict.items():
        if v is None:
            any_dict[k] = "my default value"
        elif type(v) == type(any_dict):
            replace(v)

replace(my_dict)
for k, v in my_dict.items():
    if v is None:
        my_dict[k] = "my default value"

You could do it with recursive function that iterates over all dicts and lists:您可以使用迭代所有字典和列表的递归函数来做到这一点:

def convert(obj):
    if type(obj) == list:
        for x in obj:
            convert(x)
    elif type(obj) == dict:
        for k, v in obj.iteritems():
            if v is None:
                obj[k] = 'DEFAULT'
            else:
                convert(v)

data = {1: 'foo', 2: None, 3: [{1: 'foo', 2: None}]}
convert(data)
print data # -> {1: 'foo', 2: 'DEFAULT', 3: [{1: 'foo', 2: 'DEFAULT'}]}

Here's a recursive solution that also replaces None s inside lists.这是一个递归解决方案,它也替换了列表中的None

First we define a simple class, Null , to act as the replacement for None .首先我们定义一个简单的类Null来代替None

class Null(object):
    def __repr__(self):
        return 'Null'

NULL = Null()

def replace_none(data):
    for k, v in data.items() if isinstance(data, dict) else enumerate(data):
        if v is None:
            data[k] = NULL
        elif isinstance(v, (dict, list)):
            replace_none(v)

# Test
data = {
    1: 'one', 
    2: ['two', 2, None], 
    3: None, 
    4: {4: None, 44: 'four'},
    5:  {
            5: [55, 56, None], 
            6: {66: None, 67: None},
            8: [88, {9:'nine', 99:None}, 100]
        }
}

print(data)
replace_none(data)
print(data)

output输出

{1: 'one', 2: ['two', 2, None], 3: None, 4: {44: 'four', 4: None}, 5: {8: [88, {9: 'nine', 99: None}, 100], 5: [55, 56, None], 6: {66: None, 67: None}}}
{1: 'one', 2: ['two', 2, Null], 3: Null, 4: {44: 'four', 4: Null}, 5: {8: [88, {9: 'nine', 99: Null}, 100], 5: [55, 56, Null], 6: {66: Null, 67: Null}}}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM