Python-用嵌套字典中的空字符串替换None

时间:2020-10-07 19:12:43

标签: python dictionary-comprehension

我想用Nested Dictionary中的空字符串替换None。

test={
  "order":1234,
  "status":"delivered",
   "items":[
        {
          "name":"sample1",
          "code":"ASU123",
          "unit":None
      } ],
   "product":{"name":None,"code":None}
  }

我想用空字符串替换None,并将字典的转换存储到另一个变量中,例如test1。

以下代码不允许我将其存储在另一个变量中。

def replace_none(test_dict): 
  
    # checking for dictionary and replacing if None 
    if isinstance(test_dict, dict): 
        
        for key in test_dict: 
            if test_dict[key] is None: 
                test_dict[key] = '' 
            else: 
                replace_none(test_dict[key]) 
  
    # checking for list, and testing for each value 
    elif isinstance(test_dict, list): 
        for val in test_dict: 
            replace_none(val) 
   

1 个答案:

答案 0 :(得分:0)

如@ {Pranav Hosangadi所述,您可以首先深度复制test,然后对复制的字典执行功能:

import copy
b = copy.deepcopy(test)
replace_none(b)
print(test)
print(b)

输出:

{'order': 1234, 'status': 'delivered', 'items': [{'name': 'sample1', 'code': 'ASU123', 'unit': None}], 'product': {'name': None, 'code': None}}
{'order': 1234, 'status': 'delivered', 'items': [{'name': 'sample1', 'code': 'ASU123', 'unit': ''}], 'product': {'name': '', 'code': ''}}