Reverse / invert a dictionary mapping
Python 3+:
inv_map = {v: k for k, v in my_map.items()}
Python 2:
inv_map = {v: k for k, v in my_map.iteritems()}
Reverse a dictionary to key : list of values?
d = {1:10, 2:20, 3:30, 4:30}
inv = {}
for key, val in d.iteritems():
inv[val] = inv.get(val, []) + [key]
Try this!
Reverse / invert a dictionary mapping
Python 3+:
inv_map = {v: k for k, v in my_map.items()}
Python 2:
inv_map = {v: k for k, v in my_map.iteritems()}
How do you reverse a dictionary?
Python 3
def dict_reverse(inputDict):
'''dict_reverse(inputDict) -> dict
returns dict with keys/values of inputDict swapped'''
return dict((v,k) for k,v in inputDict.items())
testDict = {'adam':80,'betty':60,'charles':50}
reversedDict = dict_reverse(testDict)
print(reversedDict)
Output {80: 'adam', 60: 'betty', 50: 'charles'}
Python reverse / inverse a mapping (but with multiple values for each key)
TL;DR
Use dictionary comprehension, like this
>>> 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 seen dictionary comprehension is functionally equivalent to the following looping structure which populates 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
shadows the built-in map
function. So, don't use that 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
, like this
>>> {value: key for key, values in my_map.items() for value in values}
{'c': 'a', 'f': 'd', 'b': 'a', 'e': 'd'}
We use items()
method here, which would create a view object from the dictionary which would give key value pairs on iteration. So we just iterate over it and construct a new dictionary with the inverse 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 don't prefer items()
method in 2.x, because it will return a list of key-value pairs. We don't want to construct a list just to iterate and construct a new dictionary. That is why we prefer iteritems()
, which returns an iterator object which gives a key value pair on iteration.
Note: The actual equivalent of Python 3.x's items
would be Python 2.x's viewitems
method, which returns a view object. Read more about the view object in the official documentation, here.
iter*
vs view*
methods in Python 2.x
The main difference between iter*
functions and view*
functions in Python 2.x is that, the view objects reflect the current state of the dictionary. For example,
>>> 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 the iter_items
, it will throw 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 view object will reflect the current state of the dictionary. So, it will work fine
>>> (2, 3) in view_items
True
The most efficient mapping/translation (with reverse option) in Python
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() }
Reverse / invert a dictionary mapping
Python 3+:
inv_map = {v: k for k, v in my_map.items()}
Python 2:
inv_map = {v: k for k, v in my_map.iteritems()}
how to invert a dictionary with multiple same values?
You are losing values because the values of the original dict (which can have duplicates) becomes keys in this one. You could do something like
inverted = defaultdict(list)
for key, value in original_dict.items():
inverted[value].append(key)
Related Topics
Error "Microsoft Visual C++ 14.0 Is Required (Unable to Find Vcvarsall.Bat)"
Best Way to Structure a Tkinter Application
How to Rotate an Image Around Its Center Using Pygame
Redirect Stdout to a File in Python
Configure Flask Dev Server to Be Visible Across the Network
How to List All Files of a Directory
Cartesian Product of X and Y Array Points into Single Array of 2D Points
Why Does the Division Get Rounded to an Integer
Why Do People Write #!/Usr/Bin/Env Python on the First Line of a Python Script
Getting Key With Maximum Value in Dictionary
How to Do Relative Imports in Python
Python + Selenium: Wait Until Element Is Fully Loaded
How to Determine the Size of an Object in Python
How to Check If String Input Is a Number
Transpose/Unzip Function (Inverse of Zip)