Bi-directional Dictionary in Python

See Python: Tips and Tricks for similar articles.

Here’s a quick function for creating a bi-directional dictionary in Python:

def bidict(d):
    d2 = d.copy()
    for k, v in d.items():
        if v in d2.keys():
            raise KeyError(
                "Cannot create bidirectional dict."
                + "Either d has a value that is the same as one of "
                + "its keys or multiple keys have the same value."
            )
        d2[v] = k
    return d2


hellos = {
    "Chinese": "你好世界",
    "Dutch": "Hello wereld",
    "English": "Hello world",
    "French": "Bonjour monde",
    "German": "Hallo Welt",
    "Greek": "γειά σου κόσμος",
    "Italian": "Ciao mondo",
    "Japanese": "こんにちは世界",
    "Korean": "여보세요 세계",
    "Portuguese": "Olá mundo",
    "Russian": "Здравствулте мир",
    "Spanish": "Hola mundo",
}

bidict(hellos)

If your original dictionary has two keys with the same value or has a value that is the same as one its keys, a KeyError will be thrown.

The new dict will look like this:

{
    "Bonjour monde": "French",
    "Chinese": "你好世界",
    "Ciao mondo": "Italian",
    "Dutch": "Hello wereld",
    "English": "Hello world",
    "French": "Bonjour monde",
    "German": "Hallo Welt",
    "Greek": "γειά σου κόσμος",
    "Hallo Welt": "German",
    "Hello wereld": "Dutch",
    "Hello world": "English",
    "Hola mundo": "Spanish",
    "Italian": "Ciao mondo",
    "Japanese": "こんにちは世界",
    "Korean": "여보세요 세계",
    "Olá mundo": "Portuguese",
    "Portuguese": "Olá mundo",
    "Russian": "Здравствулте мир",
    "Spanish": "Hola mundo",
    "γειά σου κόσμος": "Greek",
    "Здравствулте мир": "Russian",
    "こんにちは世界": "Japanese",
    "你好世界": "Chinese",
    "여보세요 세계": "Korean",
}

If you’re looking for something a little more robust, check out the bidict library.