[Tutor] Problems with deleting dictionary keys.

Allan Crooks allan.crooks@btinternet.com
Tue, 14 Aug 2001 02:07:30 +0100


On 13 Aug 2001, at 14:51, dman wrote:

<snip>

> The problem is probably that you are destroying the key while at the
> same time "creating" it.

OK, let me rewrite a different version of the code (and some 
different test output):

>>> class d2(dictionary):
...     def __setitem__(self, key, value):
...         if value==0:
...             del self[key]
...         else:
...             dictionary.__setitem__(self, key, value)
...
>>> d = d2()
>>> d.update({'a': 5})
>>> d
{'a': 5}
>>> d['a'] = 10
>>> d
{'a': 10}
>>> d['a'] = 0
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 4, in __setitem__
SystemError: NULL object passed to Py_BuildValue
>>>

As you can see, d['a'] already exists, hence I successfully turn it to 
10. But why you should deleting an existing value cause this error?

Besides, deleting a value which doesn't exist normally yields this:

>>> del {}[2]
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
KeyError: 2
>>>

I have the slightly unpleasant feeling that using deletion in the 
setitem method isn't a good idea, but I can't think how else to get 
around it.

>  Notice also that in your __setitem__ method
> you never actually set any items.

I was just using that for demonstration purposes more than 
anything. :)

> I think you want something similar to UserDict :

<snip>

Is there really any need to? Since we've got the base 'dictionary' 
type, I thought it made UserDict redundant.

But having said that, using UserDict instead of dictionary does 
work.... :)

> The proper way to delete a dictionary key is with the 'del' keyword :

Which is what the:

del self[key]

line is there for. But does this mean a dictionary (or rather a 
subclass of dictionary) cannot handle deleting items from itself?

Thanks for your help,
Allan.