Bin Chen
Bin Chen

Reputation: 63359

python: Is this a wrong way to remove an element from a dict?

I use this way to remove an emelment from a dict:

    d["ele"] = data
...
    d["ele"] = None

I think by this I can remove the reference on the original element so that the removed data can be freed, no memory leak.

Is it the right way to do this?

Upvotes: 4

Views: 422

Answers (2)

Muhammad Alkarouri
Muhammad Alkarouri

Reputation: 24672

You remove an element from a dictionary using del:

>>> d={}
>>> d['asdf']=3
>>> d['ele']=90
>>> d
{'asdf': 3, 'ele': 90}
>>> d['ele']=None
>>> d
{'asdf': 3, 'ele': None}
>>> del d['ele']
>>> d
{'asdf': 3}
>>> 

Upvotes: 11

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799300

That does not remove the key, just the value.

del d['ele']

Upvotes: 3

Related Questions