簡體   English   中英

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

[英]Python - 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}
  }

我想用空字符串替換 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) 
   

正如@ 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': ''}}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM