[Python-Dev] d.get_key(key) -> key?

Daniel 'eikeon' Krech eikeon@eikeon.com
05 Jun 2002 15:43:27 -0400

While attempting to "intern" the nodes in our rdflib's triple store I have come across the following question.

Is there or could there be an efficient way to get an existing key from a dictionary given a key that is == but whose id is not. For example:

    given a==b and id(a)!=id(b) and d[a] = 1

what is the best way to:

    d.get_key(b) -> a

--eikeon, http://eikeon.com/

PS: Here is the code where I am trying to get rid of multiple instances of equivalent nodes:


and a not so efficient first attempt:

# (could use a s.get(e2)->e1 as well given e1==e2 and id(e1)!=id(e2))

class Set(object):
    def __init__(self):
        self.__set = []

    def add(self, obj):
        e = self.get(obj)
        if e: # already have equivalent element, so return the one we have
            return e
            return obj

    def get(self, obj):
        if obj in self.__set:
            for e in self.__set:
                if e==obj:
                    return e
        return None

class Intern(object):

    def __init__(self):
        super(Intern, self).__init__()
        self.__nodes = Set()
    def add(self, subject, predicate, object):
        subject = self.__nodes.add(subject)
        predicate = self.__nodes.add(predicate)
        object = self.__nodes.add(object)
        super(Intern, self).add(subject, predicate, object)