user8211795
user8211795

Reputation: 67

Delete nested objects using python dpath library

I want to perform a delete operation using python's dpath and delete the nested objects using the separator parameter. But I cannot delete the nested objects. Below is my code

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

After the delete operation, the dictionary is {'a': {'b': {}}} whereas the the desired dictionary is {'a':{}}

Updated: I want the ability to delete one key after another under the object b and finally delete the empty b itself. Expected result should be {'a':{}}

Upvotes: 0

Views: 155

Answers (1)

BioGeek
BioGeek

Reputation: 22887

To loop over the dictionary to get your desired result, first build up your list of glob queries and then execute them one after another. You can't construct the queries and do the deletions while you're looping over the dictionary because then you would get dictionary changed size during iteration errors.

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)

Output:

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': {}}

Upvotes: 0

Related Questions