Integer and String Dictionary Keys for Fast Access

Robert k.robert at gmx.de
Sun Oct 6 15:10:28 EDT 2002


in fact python has automatic interned/hashed strings (look also for 'intern'
in
the help files). so they are same speed as integers for dict lookup as long
as you do not compose the strings freshly.

2 keys on one object?

in static or simple cases simply 2 dicts with (refs on the) same objects do
this. weakref.WeakValueDictionary is helpful some times.

For symmetric kill automation you could start like this:
-----
from weakref import ref

_JointDict__common={}
class JointDict(dict):
    def __setitem__(self, key, obj):
        __common[obj]=obj
        dict.__setitem__(self,key, weakref.ref(obj))
    def __getitem__(self, key):
        o=dict.__getitem__(self,key)
        return __common[o()]
    def killeverywhere(obj):
        del __common[obj]
    killeverywhere=staticmethod(killeverywhere)
    def __contains__(self, key):
        return dict.__getitem__(self,key)() in __common
    #def __iter__, get, ...

class X: a=1

d1=JointDict()
d2=JointDict()
d1[4]=d2["robert"]=x=X()
d1.killeverywhere(x)
print "robert" in d2    #->0

-----

Robert





More information about the Python-list mailing list