1

I am trying to build a simple dictionary of all us english vs uk english differences for a web application I am working on.

Is there a non-hacky way to build a dictionary where both the value and key can be looked up in python as efficiently as possible? I'd prefer not to loop through the dict by values for us spelling. For example:

baz = {'foo', 'bar'}
# baz['foo'] => 'bar'
# baz['bar'] => 'foo'
Matt
  • 501
  • 3
  • 13
  • 4
    Use two different dict's with the reverse mappings, or put them all into one dict. – juanpa.arrivillaga Mar 19 '20 at 04:43
  • 2
    Look at [bidict](https://github.com/jab/bidict). – wim Mar 19 '20 at 04:44
  • 2
    Adding on to @juanpa.arrivillaga's suggestion, you can also implement your own bi-directional dictionary. Refer [this](https://stackoverflow.com/questions/3318625/how-to-implement-an-efficient-bidirectional-hash-table). – Ajay Dabas Mar 19 '20 at 04:45
  • Thanks @AjayDabas I really liked [This](https://stackoverflow.com/a/3318808/872097) – Matt Mar 19 '20 at 04:51

2 Answers2

0

You can simply make reverse dict via dictionary comprehension:

baz = {'foo': 'bar'}
reversed_baz = {v: k for k, v in baz.items()}
print(reversed_baz)
baz.update(reversed_baz)
print(baz)
print(baz['foo'])
print(baz['bar'])

output:

{'bar': 'foo'}
{'foo': 'bar', 'bar': 'foo'}
bar
foo
Boseong Choi
  • 2,566
  • 9
  • 22
0

You can also make two lists one for us and the other for uk. Then append words in the lists in the same time then they would have same index in their lists just like:
Uk = [ 'foo1', bar1']
Us = [ 'foo2', 'bar2']
With these lists you can look up like this:
Us[ Uk.index('foo1') ]
The phrase in brackets will return foo1 index in Uk list then it will look like:
Us [0]
So that will return foo2.
You can do it vice versa.

Parsa Akbari
  • 108
  • 7