Can dictionary values access their keys?

Diez B. Roggisch deetsNOSPAM at web.de
Fri Apr 8 12:27:49 EDT 2005


Matthew Thorley wrote:

> Can you please elaborate on this?

Eh, just have two dicts that are the inverse of each other. You could do
that by subclassinc dict:

class mydict(dict):
    def __init__(self):
        self.__inverse_mapping = {}

    def __setitem__(self, key, value):
        dict.__setitem__(key, value)
        self.__inverse_mapping[value] = key


    def key4value(self, v):
        return self.__inverse_mapping[v]


But of course this only works if your mapping is bijective. Consider this:

d = mydict()
d[10] = 20
print d.key4value(20)
d[15] = 20
print d.key4value(20)

This will of course not give you (10,15), but 15 only - the last mapping
overwrites earlier ones. And beware of non-hashable objects like lists or
dicts themselves, they aren't working as keys. So this produces an error:

d[100] = [1,2,3,4]
TypeError: list objects are unhashable





-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list