brthornbury
brthornbury

Reputation: 3696

How to delete object in a dict by reference from another variable

So I have nested dictionary objects

a = {'a':{'b':[1,2,3]}}

And I have a reference to the nested 'b':

c=a['a']['b']

Now when I call

del c
print a

The results are

{'a':{'b':[1,2,3]}}

The variable c is deleted but the object it referenced still exists. I want to delete the nested 'b' object altogether. It is easy to do this with

del a['a']['b']

But in the real application of this, the nesting is too deep and this is used too often for that to be feasible.

The question: How do I delete a dictionary tag with only a reference to it in another variable?

Upvotes: 3

Views: 1696

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121584

del deals with the provided reference only; it cannot remove references to the same value elsewhere. That's not how Python works.

Store the path in the nested structure:

path = ('a', 'b')

You can resolve such a path:

def resolve_path(dictionary, path):
    return reduce(dict.get, path, dictionary)

or you can get the parent, after which you can delete the last element:

def del_endpoint(dictionary, path):
    parent_path, last = path[:-1], path[-1]
    parent = resolve_path(dictionary, parent_path)
    del parent[last]

This is of course very specific to nested dictionaries; for attributes or list items you'll need additional code.

Upvotes: 4

Related Questions