key - key pairs

Ivan Van Laningham ivanlan at pauahtun.org
Thu Jun 23 17:35:17 EDT 2005


Hi All--

Terry Hancock wrote:
> 
> On Thursday 23 June 2005 02:40 pm, Florian Lindner wrote:
> > is there in python a kind of dictionary that supports key - key pairs?
> > I need a dictionary in which I can access a certain element using two
> > different keys, both unique.
> >
> > For example:
> >
> > I've a dictionary with strings and times. Sometimes I have the string and I
> > want to have the time, other time I've the time and I want the string. It
> > is important that one of the keys supports the min/max builtin function.
> 
> Well, really, you're always using one or the other as the "key" and the other
> as the "value".  Furthermore, it is not in the general case assured that you
> can do this --- the keys may not really be 1:1.
> 
> If you are content to restrict yourself to the 1:1 case, you can construct
> an inverse dictionary from the first dictionary like this:
> 
> time2string = dict([ (b,a) for a,b in string2time.items() ])
> 
> Note that if string2time has duplicate values, this will arbitrarily pick
> one (in a consistent, but implementation dependent way) to use as
> the key in the inverse mapping.
> 

Well, Florian said, "using two different keys, both unique"; if that is
true, then a single key maps to a single value & vice versa.  Easiest
way, it seems to me, would be to subclass dict and provide get/set that
always insert the value as a key.  So that dict["string"]=time also
means dict[time]="string".  Only one dict required then.

Or am I missing something?

Metta,
Ivan
----------------------------------------------
Ivan Van Laningham
God N Locomotive Works
http://www.andi-holmes.com/
http://www.foretec.com/python/workshops/1998-11/proceedings.html
Army Signal Corps:  Cu Chi, Class of '70
Author:  Teach Yourself Python in 24 Hours



More information about the Python-list mailing list