简体   繁体   English

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

[英]Python - Replace None with empty string in Nested Dictionary

I want to replace None with empty string in Nested Dictionary.我想用嵌套字典中的空字符串替换 None 。

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

I want to replace None with an empty string and store conversion of the dictionary into another variable like test1.我想用空字符串替换 None 并将字典的转换存储到另一个变量中,例如 test1。

The following code is not allowing me to store it in another variable.以下代码不允许我将其存储在另一个变量中。

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) 
   

as @ Pranav Hosangadi mentioned, you can deep-copy test at first and then perform your function on the copied dict:正如@ Pranav Hosangadi提到的,您可以首先进行深拷贝test ,然后在复制的字典上执行您的功能:

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

output:输出:

{'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': ''}}

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

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