Hash map with multiple keys per value ?

Bengt Richter bokr at oz.net
Sat Nov 12 20:31:56 CET 2005

On Fri, 11 Nov 2005 22:55:53 +0000, Chris Stiles <b9a9-3arx at spamex.com> wrote:

>Hi --
>I'm working on something that includes the concept of multiple aliases for a
>particular object, where a lookup for any of the aliases has to return all the
>others.  The hack way of doing this was to have a dictionary where each 
>entry consisted of a list of all the aliases - with multiple references to the
>same list from the various dictionary entries corresponding to each alias.
What about the "particular object" in this? If all the aliases refer to the
"particular object", what does "return all the others" mean? All _what_ "others"?
All refer to the same "particular object". Or do you want the names? If so,
What about the "particular object"? Or do you want a dict back that has all the
other alias names as keys all referring to the "particular object"? E.g.,

 >>> class Aliad(dict):
 ...     def __getitem__(self, key):
 ...         keyval = dict.__getitem__(self, key)
 ...         return Aliad((k,v) for k,v in self.items() if k!=key and v is keyval)
 >>> po = 'particular object'
 >>> ad = Aliad(x=po, y=po, z=po)
 >>> ad
 {'y': 'particular object', 'x': 'particular object', 'z': 'particular object'}
 >>> ad['x']
 {'y': 'particular object', 'z': 'particular object'}
 >>> ad['y']
 {'x': 'particular object', 'z': 'particular object'}
 >>> ad['z']
 {'y': 'particular object', 'x': 'particular object'}
 >>> po2 = 'alpha'
 >>> ad.update(a=po2, b=po2, c=po2, d=po2, e=po2)
 >>> ad['x']
 {'y': 'particular object', 'z': 'particular object'}
 >>> ad['a']
 {'c': 'alpha', 'b': 'alpha', 'e': 'alpha', 'd': 'alpha'}
 >>> ad['b']
 {'a': 'alpha', 'c': 'alpha', 'e': 'alpha', 'd': 'alpha'}

And since an Aliad instance is being returned,

 >>> ad['a']
 {'c': 'alpha', 'b': 'alpha', 'e': 'alpha', 'd': 'alpha'}
 >>> ad['a']['e']
 {'c': 'alpha', 'b': 'alpha', 'd': 'alpha'}
 >>> ad['a']['e']['b']
 {'c': 'alpha', 'd': 'alpha'}
 >>> ad['a']['e']['b']['c']
 {'d': 'alpha'}
 >>> ad['a']['e']['b']['d']
 {'c': 'alpha'}

>Is there an easier and cleaner way of doing this ?  Is there example code
>floating around that I might have a look at ?
Please show _any_ example code that does (tested ;-) _exactly_ what you want.
Then we can try for an easier and cleaner way ;-)

Hope the above helps to clarify requirements one way or another ;-)

Bengt Richter

More information about the Python-list mailing list