Dictionaries inside out

Ben Finney ben+python at benfinney.id.au
Fri Nov 26 23:18:21 CET 2010

(Replying to Greg, though his original message doesn't appear at Gmane.)

> Greg Lindstrom <gslindstrom at gmail.com> writes:
> > I am working on a project where I'm using dictionaries to hold the
> > translations to codes (i.e., {'1':'Cheddar','2':'Ice
> > Hockey','IL':'Thermostat Broken'}).  The bulk of the application
> > requires me to translate codes to their meaning, but it would be nice
> > to be able to translate a meaning back to the original code as
> > well. 

If the dict is small and static, and you are sure that each value is
unique, I would say simply create the reverse mapping::

    desc_by_code = {
        '1': "Cheddar",
        '2': "Ice Hockey",
        'IL': "Thermostat Broken",

    code_by_desc = dict(
        (desc, code) for (code, desc) in codes_to_messages.items())

> > This seems to me like it must be a common situation that has been
> > addresses/solved by those smarter than me.  Is there, dare I say, a
> > design pattern for this problem?

Yes, a relational database. That might be too much overhead though.

> > Is there a better way of approaching
> > it other than making a set of dictionaries which "mirror" the
> > originals?  FWIW, I have approximately 50 tables ranging from 2
> > entries to over 100.

You may have crossed the threshold where a relational database becomes
more useful than a bunch of dicts. SQLite is built into Python, and can
store its database in memory or in a single file.

If the overhead of a database layer is too much, then creating the
reverse mappings automatically (as above) is simple enough and works

 \         “The double standard that exempts religious activities from |
  `\       almost all standards of accountability should be dismantled |
_o__)                   once and for all.” —Daniel Dennett, 2010-01-12 |
Ben Finney

More information about the Python-list mailing list