python - 从嵌套字典中删除所有 None 值
问题描述
我在示例中有以下嵌套字典json
:
{
"DICT": {
"List of dict": [
{ #first dict inside the outer list
"K1": "V1",
"K2": "V2",
"K3": "V3",
"K4": [
{
"K4_1_1": "V4_1"
},
{
"K4_2_1": "V4_2"
},
{
"K4_3_1": null
}
],
"K5 is a list of Dict": [
{
"K5_1_1": "V5_1",
"K5_1_2": "V5_2",
"K5_1_3": "V5_3",
"K5_1_4": "V5_4"
},
{
"K5_2_1": "V5_1",
"K5_2_2": "V5_2",
"K5_2_3": "V5_3",
"K5_2_4": "V5_4"
}
]
},
{ #second dict in the outerlist
"K1": "V1",
"K2": "V2",
"K3": "V3",
"K4": [
{
"K4_1_1": "V4_1_1"
},
{
"K4_2_1": "V4_2_1"
}
],
"K5": {
"K5_1_1": "V_1_1",
"K5_1_2": "V_1_2",
"K5_1_3": null,
"K5_1_4": null
}
}
]
}
}
请注意,K4
和K5
始终list
属于dict
。无论它们在字典中或列表中有多深,我都需要摆脱所有 null 。所以我写了下面的python函数,但是输出是一样的,所有的None
值都还在:
def RemoveNones(Dict):
for k, v in Dict.items():
if type(v) == collections.OrderedDict:
RemoveNones(v)
elif type(v) == list:
for i in v:
RemoveNones(i)
else:
Dict = dict((K,V) for K,V in Dict.items() if V!=None)
我里面的字典不是dict
但是<class 'collections.OrderedDict'>
。
解决方案
for 的语法type()
是这样的:if type(v) is list:
(not ==
)
所以你想要这样的东西:
import json
from collections import OrderedDict
raw_text = '{"DICT":{"List of dict":[{"K1":"V1","K2":"V2","K3":"V3","K4":[{"K4_1_1":"V4_1"},{"K4_2_1":"V4_2"},{"K4_3_1":null}],"K5 is a list of Dict":[{"K5_1_1":"V5_1","K5_1_2":"V5_2","K5_1_3":"V5_3","K5_1_4":"V5_4"},{"K5_2_1":"V5_1","K5_2_2":"V5_2","K5_2_3":"V5_3","K5_2_4":"V5_4"}]},{"K1":"V1","K2":"V2","K3":"V3","K4":[{"K4_1_1":"V4_1_1"},{"K4_2_1":"V4_2_1"}],"K5":{"K5_1_1":"V_1_1","K5_1_2":"V_1_2","K5_1_3":null,"K5_1_4":null}}]}}'
raw_json = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(raw_text)
def remove_nulls(x):
if type(x) is list:
return [remove_nulls(v) for v in x if v is not None]
elif type(x) is OrderedDict:
return OrderedDict((k,remove_nulls(v)) for k,v in x.items() if v is not None)
else:
return x
de_nullified_json = remove_nulls(raw_json)
print(json.dumps(de_nullified_json, indent=2))
输出:
{
"DICT": {
"List of dict": [
{
"K1": "V1",
"K2": "V2",
"K3": "V3",
"K4": [
{
"K4_1_1": "V4_1"
},
{
"K4_2_1": "V4_2"
},
{}
],
"K5 is a list of Dict": [
{
"K5_1_1": "V5_1",
"K5_1_2": "V5_2",
"K5_1_3": "V5_3",
"K5_1_4": "V5_4"
},
{
"K5_2_1": "V5_1",
"K5_2_2": "V5_2",
"K5_2_3": "V5_3",
"K5_2_4": "V5_4"
}
]
},
{
"K1": "V1",
"K2": "V2",
"K3": "V3",
"K4": [
{
"K4_1_1": "V4_1_1"
},
{
"K4_2_1": "V4_2_1"
}
],
"K5": {
"K5_1_1": "V_1_1",
"K5_1_2": "V_1_2"
}
}
]
}
}
推荐阅读
- node.js - 如何从异步函数中获取某些数据?
- python - OpenCV 和 Mediapipe 面部模糊污迹
- android - 浓缩咖啡测试:未正确设置 TestNavHostController.setCurrentDestination
- xslt - 如何使用 XSLT 将一个文档中的特定文本提取到一个新文档中?
- typescript - 如何支持类 mixin 的对象合并
- postgresql - 两列 A 和 B,表 Y (A, B) 参考表 X (A, B)。当 Y 中的 A 发生变化时,如何使 Y 中的 B 更改为引用的表 X 值?
- flutter - 如何在flutter中验证号码电话的身份验证后停止登录
- javascript - 创建用户控件
- mysql - MySQL 链式替换?
- flutter - 我想在 statefulWidget 中使用 bloc 获取发布数据数据已准备好我不会从 api 获取它 oi 怎么做?