[英]How to get a list of dict that each dict is coming from the same original dict with only one key removed?
我的场景:我需要遍历嵌套的 json object,返回一个 json object 的列表,每个都删除了一个键。 而且您不知道原始数据的结构。
至于我 go:我写了一个递归 function 来打印 object 中的每个键值。它有效。 但这不是我想要的。
定义返回:这个function得到一个dict,返回一个dict列表,每个dict都是原dict去掉一个key后的副本。
如果字典从一开始就有 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 一样返回列表字典。
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。 它最初给了我所有“叶”项目的 jsonpath。 所以我稍微更改了源代码以获取每个键的 jsonpath。
第二个 jsonpath_ng 让我用 jsonpath 过滤一个键。
通过一些数据操作,我得到了我想要的结果。
这是为了如果有人遇到与我相同的情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.