0

I have several lists of tuples similar to (city_name, city_code) which I store in dictionary for practical reasons so I can easily map city_name to city_code. Obviously both city name and code are unique.

It is easy to retrieve the code of the city based on its name but sometimes I would like to be able to do it another way around like getting the name of the city from the code for which I do linear search among dictionary items which is pretty clumsy.

for c in cities.items():
           if c[1] == code:
                name = c[0]
                break

Is there a a better way to do this? I am using python 2.7.8 and I would like to keep this simple without any additional modules.

ps-aux
  • 11,627
  • 25
  • 81
  • 128

2 Answers2

0

It is easy enough to make a reverse dictionary. Suppose we have a dictionary d:

In [9]: d
Out[9]: {'LA': 11, 'NO': 12, 'NYC': 10, 'SF': 13}

A dictionary which reverses keys and values can be generated:

In [10]: reverse_d = dict((v, k) for k, v in d.items())

In [11]: reverse_d
Out[11]: {10: 'NYC', 11: 'LA', 12: 'NO', 13: 'SF'}
John1024
  • 109,961
  • 14
  • 137
  • 171
0

You sound like you want to make a bidirectional dictionary:

class Bidict:
    def __init__(self):
        self.data = {}
        self.reverse = {}
    def __setitem__(self, k, v):
        self.data[k] = v
        self.reverse[v] = k
    def __getitem__(self,k):
        return self.data[k]
    def getKey(self, v):
        return self.reverse[v]

Output:

In [119]: bd = Bidict()

In [120]: bd[1] = 'a'

In [121]: bd
Out[121]: <__main__.Bidict at 0x10b0b8be0>

In [122]: bd.data
Out[122]: {1: 'a'}

In [123]: bd.reverse
Out[123]: {'a': 1}

In [124]: bd[1]
Out[124]: 'a'

In [125]: bd.getKey['a']
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-125-59e1828d8af1> in <module>()
----> 1 bd.getKey['a']

TypeError: 'method' object is not subscriptable

In [126]: bd.getKey('a')
Out[126]: 1
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241