key - key pairs

Paul McGuire ptmcg at
Fri Jun 24 21:09:41 CEST 2005

Man, this is not my week!  Another bug in my posted code!  The posted
version of SymmetricDict fails when adding an entry in which the key
equals the value.  First bug is in __setitem__ in which the insertion
is done twice, which is wasteful but benign.  The second bug is in
__delitem__, which throws an exception when we try to delete the
back-pointing entry - which was already deleted since there is only one

Another cautionary tale on the value of testing...

Here it the improved SymmetricDict code.

-- Paul

class SymmetricDict(dict):
    def __delitem__(self,k):
        v = self[k]
        if not v==k:

    def __setitem__(self,k,v):
        if k in self:
            del self[k]
        if v in self:
            del self[v]
        if not v==k:

More information about the Python-list mailing list