Given a dictionary like so:
my_map = { 'a': 1, 'b':2 }
How can one invert this map to get:
inv_map = { 1: 'a', 2: 'b' }
EDITOR NOTE: map
changed to my_map
to avoid conflicts with the built-in function, map
. Some comments may be affected below.
Not something completely different, just a bit rewritten recipe from Cookbook. It's futhermore optimized by retaining
setdefault
method, instead of each time getting it through the instance:Designed to be run under CPython 3.x, for 2.x replace
mapping.items()
withmapping.iteritems()
On my machine runs a bit faster, than other examples here
This expands upon the answer Python reverse / invert a mapping, applying to when the values in the dict aren't unique.
The implementation is limited in that you cannot use
reversed
twice and get the original back. It is not symmetric as such. It is tested with Python 2.6. Here is a use case of how I am using to print the resultant dict.If you'd rather use a
set
than alist
, and there are applications for which this makes sense, instead ofsetdefault(v, []).append(k)
, usesetdefault(v, set()).add(k)
.In addition to the other functions suggested above, if you like lambdas:
Or, you could do it this way too:
Adding my 2 cents of pythonic way:
Example:
This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}
I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":
Deletion and iteration methods are easy enough to implement if they're needed.
This implementation is way more efficient than inverting an entire dictionary (which seems to be the most popular solution on this page). Not to mention, you can add or remove values from your SymDict as much as you want, and your inverse-dictionary will always stay valid -- this isn't true if you simply reverse the entire dictionary once.