TL DR
Use a dictionary understanding like
>>> my_map = { 'a': ['b', 'c'], 'd': ['e', 'f'] } >>> {value: key for key in my_map for value in my_map[key]} {'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'}
The above dictionary understanding is functionally equivalent to the following loop structure, which fills an empty dictionary
>>> inv_map = {} >>> for key in my_map: ... for value in my_map[key]: ... inv_map[value] = key ... >>> inv_map {'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'}
Note. . Using map obscures the built-in map function. Therefore, do not use this as a variable name unless you know what you are doing.
Other similar ways to do the same.
Python 3.x
You can use dict.items for example
>>> {value: key for key, values in my_map.items() for value in values} {'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'}
We use the items() method here, which would create a view object from a dictionary that would give pairs of key values ββin an iteration. Therefore, we simply iterate over it and build a new dictionary with reverse mapping.
Python 2.x
You can use dict.iteritems like this
>>> {value: key for key, values in my_map.iteritems() for value in values} {'c': 'a', 'b': 'a', 'e': 'd', 'f': 'd'}
We do not prefer the items() method in 2.x because it will return a list of key-value pairs. We do not want to create a list only for iterating and building a new dictionary. Therefore, we prefer iteritems() , which returns an iterator object that gives a pair of key values ββin an iteration.
Note: The actual equivalent of Python 3.x items will be Python 2.x viewitems , which returns a view object. Read more about the object of presentation in the official documentation, here .
iter* vs view* in Python 2.x
The main difference between the iter* functions and the view* functions in Python 2.x is that view objects reflect the current state of the dictionary. For instance,
>>> d = {1: 2} >>> iter_items = d.iteritems() >>> view_items = d.viewitems()
now we add a new element to the dictionary
>>> d[2] = 3
If you try to check if (2, 3) (key-value pair) is in iter_items , this will cause an error
>>> (2, 3) in iter_items Traceback (most recent call last): File "<input>", line 1, in <module> RuntimeError: dictionary changed size during iteration
but the viewer will display the current state of the dictionary. This way it will work fine
>>> (2, 3) in view_items True