如何获得一个字典列表,每个字典都来自同一个原始字典,只有一个键被删除?



我的场景:我需要迭代通过一个嵌套的json对象,得到返回json对象的列表,每个有一个键被删除。而且你不知道原始数据的结构。

在我看来:我写了一个递归函数来打印对象中的每个键值。它的工作原理。但这不是我想要的。

定义返回:此函数获取一个dict并返回一个dict列表,每个dict都是删除一个键后的原始dict的副本。

如果字典从一开始就有3个键,那么我应该得到3个字典,每个字典都有1个键被删除。

如果键有嵌套值,它们也应该被删除。例如,如果键恰好是根键,那么它仍然是一个空字典。

下面是我的代码:

def iterate_keys(data: dict):
# This is as far as I can go
for key, value in data.items():
if type(value) in [dict, ]:
iterate_keys(value)
elif type(value) in [list, ]:
for item in value:
if type(item) in [dict]:
iterate_keys(item)
print(key, value)
# def what_i_really_want(data: dict) -> list:
# return [dict1, dict2, ...]
if __name__ == '__main__':
test_dict = {
"a": "a",
"c": {
"c1": [
{"c11": "c11"},
{"c12": "c12"},
]
},
}
iterate_keys(test_dict)

对于代码中的test_dict,理想情况下它应该返回像blow这样的列表dict。

result_should_be = [
{
# with "a" removed
"c": {
"c1": [
{"c11": "c11"},
{"c12": "c12"},
]
}
},
# with "c11" removed
{
"a": "a",
"c": {
"c1": [
{"c12": "c12"},
]
}
},
# with "c12" removed
{
"a": "a",
"c": {
"c1": [
{"c11": "c11"},
]
}
},
# with "c1" removed
{
"a": "a",
"c": {}
},
# with "c" removed
{
"a": "a"
},
]

在一天结束时,我创建了一堆测试用例。希望我讲清楚了

我真的很纠结。我设法用两个库解决了这个问题。

第一个jsonpathgenerator获取原始数据的所有jsonpath。它最初给了我所有'leaf'项目的json路径。因此,我稍微更改了源代码,以获取每个键的jsonpath。

第二个jsonpath_ng让我用jsonpath过滤一个键。

和一些数据操作,我得到了我想要的结果。

如果有人遇到和我一样的情况,这是为你准备的。

最新更新