0

I need a bi-direction lookup, and to keep the code DRY I don't want to write the values twice, the simplest thing I can come up with is to create the reverse lookup from the original like this:

>>> lookup1 =  {1:'one', 2:'two'}
>>> lookup2 = dict([(v,k) for (k,v) in lookup1.items()])
>>> lookup2.get('two')
2

But is there a more pythonic way of doing this?

The dicts are not very large (dozens of items at most) so performance is not the paramount concern.

(I am restricted to v2.6)

Paul McKenzie
  • 19,646
  • 25
  • 76
  • 120
  • possible duplicate of [Python bidirectional mapping](http://stackoverflow.com/questions/9282997/python-bidirectional-mapping) – BartoszKP Feb 28 '14 at 10:22
  • also you might want to look at http://stackoverflow.com/questions/3318625/efficient-bidirectional-hash-table-in-python – BartoszKP Feb 28 '14 at 10:23
  • "to keep the code DRY I don't want to write the values twice" - how is your solution going to keep the code DRY? The right way(TM) would be to encapsulate lookup and reverse-lookup functionality in one object, and hide how it's implemented. – Karoly Horvath Feb 28 '14 at 10:26
  • @KarolyHorvath yes, the thing is encapsulated, it's the implementation that I am asking about. – Paul McKenzie Feb 28 '14 at 10:42
  • You don't need '[' and ']' when creating the lookup2 dict. – pasztorpisti Feb 28 '14 at 11:34

0 Answers0