Worthwhile to reverse a dictionary

Larry Bates larry.bates at websafe.com
Thu Dec 15 13:28:40 EST 2005


rudysanford at hotmail.com wrote:
> I just started messing with programming and started with Python.  Part
> of my first project deals with translating numerical values to letters.
> I would like to be able to do the reverse as well, letters to numbers,
> sort of a table for lookup and a table for reverse lookup.  I thought
> that a dictionary would be the structure to use- write it once and in a
> second instance swap the keys for values and values for keys.  However,
> reversing a dictionary does not seem to be easily achieved.  Am I using
> the wrong data structure?
> 
This doesn't really answer your question (others have already done this),
but back in the 'ol days we did this:

>>> letters=['a','b','c']
>>> map(lambda x: ord(x)-64, letters)
[1, 2, 3]

This takes advantage of the fact that letters must be stored as
binary integers in ASCII (e.g. 'a' = 65, 'b'=66, etc.).  You can
go the other direction with chr(x).  Not completely sure about
what you want to accomplish, but this eliminates the need for
the dictionaries.

Larry Bates



More information about the Python-list mailing list