python - Python - 用嵌套字典中的空字符串替换无
问题描述
我想用嵌套字典中的空字符串替换 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': ''}}
推荐阅读
- python - 为什么`ctypes`比扩展python慢?
- c - MPLABX XC16 无法解析内置标识符 __builtin_dmaoffset
- ios - Swift:UILabel,闪烁 textColor 动画
- firebase - 开始使用适用于 Firebase 和 Firestore 的 Cloud Functions
- javascript - 如何使用ajax访问两个不同的对象?
- vue.js - 如何在 VueJS 中制作图像网格堆栈?
- python - 将 tf.data.Dataset 包装到 tf.function 中会提高性能吗?
- javascript - 如何管理 Vue 反应性?
- java - 转换为字符串到json
- java - azure-sql 中不允许使用 Hibernate 调用的 USE 语句,如何避免?