Dictionary bidirectional

Gerry gerard.blais at gmail.com
Mon Jul 14 16:24:28 CEST 2008


If keys and values are unique, maybe just store both in the same
dictionary:

   mydict[a] = b
   mydict[b] = a

   ...

   Gerry

On Jul 14, 8:31 am, Impotent Verse <simon.pever... at gmail.com> wrote:
> If keys and values are unique you could do this...
>
> --------------
>
> #         Left      : Right
> roman = { "One"     : "I",
>           "Two"     : "II",
>           "Three"   : "III",
>           "Four"    : "IV",
>           "Five"    : "V",
>           "Six"     : "VI",
>           "Seven"   : "VII",
>           "Eight"   : "VIII",
>           "Nine"    : "IX",
>           "Ten"     : "X" }
>
> left, right = zip( *roman.items() )
> left = list(left)
> right = list(right)
>
> print left[ right.index("VIII") ]
>
> --------------
>
> ... result is "Eight".
>
> Hmmm! zip returns tuples, which need to be turned into lists to do
> much with. Maybe not the best solution in this case.
>
> Verse.




More information about the Python-list mailing list