为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

潇湘沐 2023-10-18 16:11:59
我想用嵌套字典中的空字符串替换 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 回答

?
慕仙森

TA贡献1827条经验 获得超7个赞

您可以首先进行深度复制,然后对复制的字典执行您的功能:


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


查看完整回答
反对 回复 2023-10-18
  • 1 回答
  • 0 关注
  • 83 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信