Dictionary, keys and alias
Steven D'Aprano
steve at REMOVETHIScyber.com.au
Mon Jul 18 09:18:48 EDT 2005
On Mon, 18 Jul 2005 12:17:37 +0200, Glauco wrote:
> I want to insert a concept of alias in a dict_based class.
>
> The idea is to have a facoltative name in the same dict that correspond
> at the same value. With this alias i can change original value.
>
> example:
>
> mydict['a'] = 1
> I must define an alias example: myFunctAlias( mydict, 'a', 'b')
> print mydict
> {'a':1, 'b':1}
> mydict['b'] = 2
> print mydict
> {'a':2, 'b':2}
>
>
> The only idea i have is to implement two dictionary one for convert
> name, alias in two keys with the same value (eg.numeric) in the first
> dict. The second for store only one time the k, v .
You need some sort of redirection, something like this (untested):
class Doubledict:
def __init__(self, **kargs):
self.data = {}
self.aliases = {}
for key in kargs:
# Point the key to a hash.
self.aliases[key] = hash(key)
# And point the hash at the value.
self.data[hash(key)] = kargs[key]
def setalias(self, key, alias):
# Point the alias to the same hash as the real key.
self.aliases[alias] = hash(key)
def __getitem__(self, key):
return self.data[self.aliases[key]]
def __setitem__(self, key, value):
self.data[self.aliases[key]] = value
The only niggly worry I have is I'm not sure when hash can be used, when
it is unique, or even if is it guaranteed to be unique.
--
Steven.
More information about the Python-list
mailing list