No need to update __getitem__, since the modified __setitem__ drops in
the reverse values.  But __delitem__ needs overriding, and some special
guard needs to be added to __setitem__ to prevent orphaning any old
value:key entries.

-- Paul


Here's one possible solution:

class SymmetricDict(dict):
    def __delitem__(self,x):
        v = self[x]
        super(SymmetricDict,self).__delitem__(x)
        super(SymmetricDict,self).__delitem__(v)
    def __setitem__(self,k,v):
        if k in self:
            del self[k]
        if v in self:
            del self[v]
        super(SymmetricDict,self).__setitem__(k,v)
        super(SymmetricDict,self).__setitem__(v,k)

sd = SymmetricDict()

sd["A"] = 1
print sd["A"]
print sd[1]
sd["A"] = 2
print sd["A"]
print sd[2]
print sd[1]

prints:

1
A
2
A
Traceback (most recent call last):
  File "symmetricDict.py", line 25, in ?
    print sd[1]
KeyError: 1

-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to