Can dictionary values access their keys?
Axel Straschil
axel at straschil.com
Fri Apr 8 12:21:22 EDT 2005
Hello!
> If I have a simple dictionary, where the value is a class or function,
> is there an interface through which it can discover what its key is?
The key of a value may not be unique, so you can also get a tupe of
keys, like dict(a=1, b=1), the key's of 1 are a and b.
For unique values, I did something like that couple of weeks ago, the
thing you would need is the getKey thing, it's fast, but needs much
memory for big structures becouse I use two dicts.
If speed does not matter:
class ReverseDict(dict):
def get_keys(self, value):
keys = []
for k, v in self.items():
if v == value: keys.append(k)
return keys
class UniqueReverseDict(dict):
"""
A dictionary that can resolute reverse: A object to a key. Both, the Key and
the Value must be unique.
"""
def __init__(self, **kws):
super(UniqueReverseDict, self).__init__(kws)
self.__reverse = {}
def __setitem__(self, k, v):
super(UniqueReverseDict, self).__setitem__(k, v)
self.__reverse[v] = k
def __update_reverse(self):
self.__reverse.clear()
for k, v in self.items():
self.__reverse[v] == k
def has_value(self, v):
return self.__reverse.has_key(v)
def __delitem__(self, k):
self.__reverse[self[k]]
super(UniqueReverseDict, self).__delitem__(k)
def clear(self):
self.__reverse.clear()
super(UniqueReverseDict, self).clear()
def copy(self):
return UniqueReverseDict(self)
def pop(self, k):
del self.__reverse[self[k]]
return self.pop(k)
def popitem(self, **kws):
raise 'AxsPy.Misc.Structures.UniqueReverseDict', \
'NotImplemented'
def setdefault(self, **kws):
raise 'AxsPy.Misc.Structures.UniqueReverseDict', \
'NotImplemented'
def update(self, **kws):
super(UniqueReverseDict, self).update(**kws)
self.__update_reverse()
def getKey(self, v): return self.__reverse[v]
Lg,
AXEL
--
"Aber naja, ich bin eher der Forentyp." Wolfibolfi's outing in
http://www.informatik-forum.at/showpost.php?p=206342&postcount=10
More information about the Python-list
mailing list