0

我想使用 python 的 dpath 执行删除操作,并使用 separator 参数删除嵌套对象。但我无法删除嵌套对象。下面是我的代码

import dpath.util
    
    dictionary = {
            "a": {
                "b": {
                    "c": 0,
                    "d": 1,
                    "e": 2,
                     }
                }
            }
dpath.util.delete(dictionary, "a.b.c", separator=".")

删除操作后,字典是{'a': {'b': {}}},而所需的字典是{'a':{}}

更新:我希望能够在对象下一个接一个地删除一个键b,最后删除空b本身。预期结果应该是{'a':{}}

4

1 回答 1

0

要遍历字典以获得您想要的结果,首先建立您的全局查询列表,然后一个接一个地执行它们。在遍历字典时不能构造查询和删除,因为那样会dictionary changed size during iteration出错。

import dpath.util

dictionary = {
        "a": {
            "b": {
                "c": 0,
                "d": 1,
                "e": 2,
                  }
            }
        }

queries = []
for key1 in dictionary:
  for key2 in dictionary[key1]:
    for key3 in dictionary[key1][key2]:
      query = f"{key1}.{key2}.{key3}"
      queries.append(query)
    query = f"{key1}.{key2}"
    queries.append(query)

for query in queries:
    print(f"Deleting with glob query: {query}")
    dpath.util.delete(dictionary, query, separator=".")
    print(dictionary)

输出:

Deleting with glob query: a.b.c
{'a': {'b': {'d': 1, 'e': 2}}}
Deleting with glob query: a.b.d
{'a': {'b': {'e': 2}}}
Deleting with glob query: a.b.e
{'a': {'b': {}}}
Deleting with glob query: a.b
{'a': {}}
于 2021-11-16T15:36:11.877 回答