Search code examples
pythondictionarylookup-tablesdictionary-comprehension

The most efficient mapping/translation (with reverse option) in Python


Consider a very large Python dictionary of the like:

some_dict = {
    "val_1": "val_a",
    "val_2": "val_b",
    "val_x": "val_1",
    "val_y": "val_2",
    ### millions of one-to-one key-value pairs
    ### note that keys and values can overlap
}

I would like to use this dictionary to efficiently convert/translate data from one representation to another (and back). What is the most efficient way of achieving this?

One option is to create some_dict_reversed and then use dictionary looks ups for inverse conversion, but I would like to avoid duplicating the data. There must be a better way.


Solution

  • If you want to use the values as keys, you need to hash them, which is what a dictionary does for you. So you'll need a second dictionary.

    If the pairs indeed represent 1-to-1 relationships, i.e. it is a bijective relationship, then:

    rev = { val: key for key, val in some_dict.items() }