Python reverse / invert a mapping












505















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.










share|improve this question

























  • dict(zip(inv_map.values(), inv_map.keys()))

    – Seshadri VS
    Sep 22 '18 at 10:33











  • @SeshadriVS, it works (for both Python 2 and Python 3, thanks! =)

    – Filipp W.
    Nov 7 '18 at 9:06


















505















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.










share|improve this question

























  • dict(zip(inv_map.values(), inv_map.keys()))

    – Seshadri VS
    Sep 22 '18 at 10:33











  • @SeshadriVS, it works (for both Python 2 and Python 3, thanks! =)

    – Filipp W.
    Nov 7 '18 at 9:06
















505












505








505


105






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.










share|improve this question
















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.







python dictionary mapping inverse






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Apr 24 '18 at 14:00







Brian M. Hunt

















asked Jan 27 '09 at 14:46









Brian M. HuntBrian M. Hunt

36.5k56177295




36.5k56177295













  • dict(zip(inv_map.values(), inv_map.keys()))

    – Seshadri VS
    Sep 22 '18 at 10:33











  • @SeshadriVS, it works (for both Python 2 and Python 3, thanks! =)

    – Filipp W.
    Nov 7 '18 at 9:06





















  • dict(zip(inv_map.values(), inv_map.keys()))

    – Seshadri VS
    Sep 22 '18 at 10:33











  • @SeshadriVS, it works (for both Python 2 and Python 3, thanks! =)

    – Filipp W.
    Nov 7 '18 at 9:06



















dict(zip(inv_map.values(), inv_map.keys()))

– Seshadri VS
Sep 22 '18 at 10:33





dict(zip(inv_map.values(), inv_map.keys()))

– Seshadri VS
Sep 22 '18 at 10:33













@SeshadriVS, it works (for both Python 2 and Python 3, thanks! =)

– Filipp W.
Nov 7 '18 at 9:06







@SeshadriVS, it works (for both Python 2 and Python 3, thanks! =)

– Filipp W.
Nov 7 '18 at 9:06














31 Answers
31






active

oldest

votes













1 2
next












702














For Python 2.7.x



inv_map = {v: k for k, v in my_map.iteritems()}


For Python 3+:



inv_map = {v: k for k, v in my_map.items()}





share|improve this answer





















  • 44





    in python2.7+, using map.iteritems() would be more efficient.

    – Mike Fogel
    Dec 4 '12 at 23:40






  • 6





    however in python 3+ just use my_map.items() as the answer shows.

    – Rick Teachey
    Aug 21 '16 at 13:03






  • 10





    @rasen58 Python dictionaries don't have an ordering

    – Anentropic
    Oct 27 '16 at 12:42






  • 4





    This'll work except that it won't work if there is not unicity in the values. In that case you'll loose some entries

    – gabuzo
    Oct 23 '17 at 16:28






  • 5





    Fun Fact: Dictionaries will be ordered (by time of insertion) in Python 3.7 onwards.

    – byxor
    Jun 12 '18 at 20:18





















162














Assuming that the values in the dict are unique:



dict((v, k) for k, v in my_map.iteritems())





share|improve this answer





















  • 17





    What if the values aren't unique?

    – Buttons840
    Apr 27 '12 at 20:34






  • 14





    The values have to be hashable too

    – John La Rooy
    May 24 '12 at 1:52






  • 25





    @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense.

    – Wrzlprmft
    Oct 25 '14 at 14:13






  • 2





    @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that iteritems() will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general.

    – Evgeni Sergeev
    Apr 21 '15 at 8:13






  • 3





    @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it.

    – Leo
    Oct 25 '16 at 19:08



















109














If the values in my_map aren't unique:



inv_map = {}
for k, v in my_map.iteritems():
inv_map[v] = inv_map.get(v, )
inv_map[v].append(k)





share|improve this answer





















  • 49





    ... or just inv_map.setdefault(v, ).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit.

    – alsuren
    Nov 10 '10 at 14:55













  • This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default

    – Yaroslav Bulatov
    Apr 22 '16 at 20:37






  • 1





    @YaroslavBulatov no, the code as shown here isn't broken - inv_map.get(v, ) returns the already-added list if there is one, so the assignment doesn't reset to an empty list. setdefault would still be prettier, though.

    – Mark Amery
    Jul 16 '16 at 17:23








  • 8





    A set would make more sense here. The keys are (probably) hashable, and there is no order. inv_map.setdefault(v, set()).add(k).

    – Artyer
    Aug 11 '17 at 17:17



















37














def inverse_mapping(f):
return f.__class__(map(reversed, f.items()))





share|improve this answer



















  • 11





    Upvoted for retaining the type rather than silently converting into dict

    – gerrit
    Nov 26 '14 at 17:25






  • 2





    @gerrit: Too bad this motivation is not explained in the answer itself. (Moreover, the answer has to explaination at all at the moment.)

    – vog
    Jan 15 '17 at 21:42






  • 1





    This... is extremely clever. While non-human-readable, this one-liner successfully preserves both the type and ordering (e.g., for OrderedDict types) of the original dictionary by passing an anonymous iterable to the dict(iterable) form of mapping constructors. Explanatory exposition would have been helpful, of course. </sigh>

    – Cecil Curry
    Dec 22 '17 at 6:37








  • 1





    Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary.

    – Rafael_Espericueta
    Jun 5 '18 at 1:02



















30














Try this:



inv_map = dict(zip(my_map.values(), my_map.keys()))


(Note that the Python docs on dictionary views explicitly guarantee that .keys() and .values() have their elements in the same order, which allows the approach above to work.)



Alternatively:



inv_map = dict((my_map[k], k) for k in my_map)


or using python 3.0's dict comprehensions



inv_map = {my_map[k] : k for k in my_map}





share|improve this answer


























  • Notice that this only works if the keys are unique (which is almost never the case if you want to invert them).

    – gented
    Jun 22 '18 at 8:26











  • According to python.org/dev/peps/pep-0274 dict comprehensions are available in 2.7+, too.

    – Kawu
    Oct 27 '18 at 1:03





















17














Another, more functional, way:



my_map = { 'a': 1, 'b':2 }
dict(map(reversed, my_map.items()))





share|improve this answer





















  • 2





    Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "filter and map should die and be subsumed into list comprehensions, not grow more variants".

    – Brian M. Hunt
    Feb 26 '14 at 16:38






  • 1





    Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess)

    – Brendan Maguire
    Feb 26 '14 at 17:10






  • 2





    In Python 3 it should be my_map.items().

    – dmvianna
    Jul 25 '16 at 23:47






  • 1





    Might be less readable than others, but this way does have the benefit of being able to swap out dict with other mapping types such as collections.OrderedDict or collections.defaultdict

    – Will S
    Aug 17 '17 at 9:51





















7














This expands upon the answer Python reverse / invert a mapping, applying to when the values in the dict aren't unique.



class ReversibleDict(dict):

def reversed(self):
"""
Return a reversed dict, with common values in the original dict
grouped into a list in the returned dict.

Example:
>>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
>>> d.reversed()
{1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
"""

revdict = {}
for k, v in self.iteritems():
revdict.setdefault(v, ).append(k)
return revdict


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 a list, and there are applications for which this makes sense, instead of setdefault(v, ).append(k), use setdefault(v, set()).add(k).






share|improve this answer


























  • this would also be a good place to use sets instead of lists, i.e. revdict.setdefault(v, set()).add(k)

    – mueslo
    Dec 22 '16 at 20:42











  • Of course, but that's exacty why it's a good reason to use set. It's the intrinsic type that applies here. What if I want to find all keys where the values are not 1 or 2? Then I can just do d.keys() - inv_d[1] - inv_d[2] (in Python 3)

    – mueslo
    Dec 22 '16 at 20:57



















6














Combination of list and dictionary comprehension. Can handle duplicate keys



{v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}





share|improve this answer

































    5














    Adding my 2 cents of pythonic way:



    inv_map = dict(map(reversed, my_map.items()))


    Example:



    In [7]: my_map
    Out[7]: {1: 'one', 2: 'two', 3: 'three'}

    In [8]: inv_map = dict(map(reversed, my_map.items()))

    In [9]: inv_map
    Out[9]: {'one': 1, 'three': 3, 'two': 2}





    share|improve this answer
























    • This is a clone of Brendan Maguire's answer which has been given three years before.

      – Adrian W
      Sep 20 '18 at 10:01



















    4














    If the values aren't unique, and you're a little hardcore:



    inv_map = dict(
    (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())])
    for v in set(my_map.values())
    )


    Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over items() multiple times.






    share|improve this answer





















    • 5





      This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion.

      – Russ Bradberry
      Oct 3 '12 at 19:19



















    4














    We may also reverse a dictionary with duplicate keys using defaultdict:



    from collections import Counter, defaultdict

    def invert_dict(d):
    d_inv = defaultdict(list)
    for k, v in c.items():
    d_inv[v].append(k)
    return d_inv

    text = 'aaa bbb ccc ddd aaa bbb ccc aaa'
    c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1})
    dict(invert_dict(c)) # {1: ['ddd'], 2: ['bbb', 'ccc'], 3: ['aaa']}


    See here:




    This technique is simpler and faster than an equivalent technique using dict.setdefault().







    share|improve this answer

































      3














      In addition to the other functions suggested above, if you like lambdas:



      invert = lambda mydict: {v:k for k, v in mydict.items()}


      Or, you could do it this way too:



      invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )





      share|improve this answer


























      • -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a PEP 8 violation.

        – Mark Amery
        Jul 16 '16 at 18:03



















      3














      This handles non-unique values and retains much of the look of the unique case.



      inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}


      For Python 3.x, replace itervalues with values.
      I can't take credit for this... it was suggested by Icon Jack.






      share|improve this answer


























      • This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one.

        – gabuzo
        Oct 24 '17 at 8:21











      • Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data.

        – Ersatz Kwisatz
        Oct 25 '17 at 17:01



















      2














      I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":



      class SymDict:
      def __init__(self):
      self.aToB = {}
      self.bToA = {}

      def assocAB(self, a, b):
      # Stores and returns a tuple (a,b) of overwritten bindings
      currB = None
      if a in self.aToB: currB = self.bToA[a]
      currA = None
      if b in self.bToA: currA = self.aToB[b]

      self.aToB[a] = b
      self.bToA[b] = a
      return (currA, currB)

      def lookupA(self, a):
      if a in self.aToB:
      return self.aToB[a]
      return None

      def lookupB(self, b):
      if b in self.bToA:
      return self.bToA[b]
      return None


      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.






      share|improve this answer


























      • I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators.

        – Brian M. Hunt
        Sep 28 '14 at 10:59











      • @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions...

        – NcAdams
        Sep 28 '14 at 20:46













      • And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later

        – NcAdams
        Sep 28 '14 at 20:47








      • 1





        "This implementation is way more efficient than inverting an entire dictionary" - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be slower than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling dictresize, but this approach denies Python that possibility.

        – Mark Amery
        Jul 16 '16 at 18:11



















      2














      Using zip



      inv_map = dict(zip(my_map.values(), my_map.keys()))





      share|improve this answer































        1














        Try this for python 2.7/3.x



        inv_map={};
        for i in my_map:
        inv_map[my_map[i]]=i
        print inv_map





        share|improve this answer

































          1














          I would do it that way in python 2.



          inv_map = {my_map[x] : x for x in my_map}





          share|improve this answer

































            1














            def invertDictionary(d):
            myDict = {}
            for i in d:
            value = d.get(i)
            myDict.setdefault(value,).append(i)
            return myDict
            print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})


            This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}






            share|improve this answer































              1














                def reverse_dictionary(input_dict):
              out = {}
              for v in input_dict.values():
              for value in v:
              if value not in out:
              out[value.lower()] =

              for i in input_dict:
              for j in out:
              if j in map (lambda x : x.lower(),input_dict[i]):
              out[j].append(i.lower())
              out[j].sort()
              return out


              this code do like this:



              r = reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})

              print(r)

              {'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}





              share|improve this answer


























              • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

                – Tom Aranda
                Dec 18 '17 at 16:17











              • It is a nice solution

                – Dr Beco
                Jul 14 '18 at 16:06











              • It's very nice, but a lot of unexplained decisions (for example, why lower case for keys?)

                – Liudvikas Akelis
                Sep 7 '18 at 12:49



















              0














              Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))



              def reverse_dict(dictionary):
              reverse_dict = {}
              for key, value in dictionary.iteritems():
              if not isinstance(value, (list, tuple)):
              value = [value]
              for val in value:
              reverse_dict[val] = reverse_dict.get(val, )
              reverse_dict[val].append(key)
              for key, value in reverse_dict.iteritems():
              if len(value) == 1:
              reverse_dict[key] = value[0]
              return reverse_dict





              share|improve this answer

































                0














                Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.



                def r_maping(dictionary):
                List_z=
                Map= {}
                for z, x in dictionary.iteritems(): #iterate through the keys and values
                Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
                return Map





                share|improve this answer

































                  0














                  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:



                  def inverse(mapping):
                  '''
                  A function to inverse mapping, collecting keys with simillar values
                  in list. Careful to retain original type and to be fast.
                  >> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
                  >> inverse(d)
                  {1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
                  '''
                  res = {}
                  setdef = res.setdefault
                  for key, value in mapping.items():
                  setdef(value, ).append(key)
                  return res if mapping.__class__==dict else mapping.__class__(res)


                  Designed to be run under CPython 3.x, for 2.x replace mapping.items() with mapping.iteritems()



                  On my machine runs a bit faster, than other examples here






                  share|improve this answer































                    0














                    If values aren't unique AND may be a hash (one dimension):



                    for k, v in myDict.items():
                    if len(v) > 1:
                    for item in v:
                    invDict[item] = invDict.get(item, )
                    invDict[item].append(k)
                    else:
                    invDict[v] = invDict.get(v, )
                    invDict[v].append(k)


                    And with a recursion if you need to dig deeper then just one dimension:



                    def digList(lst):
                    temp =
                    for item in lst:
                    if type(item) is list:
                    temp.append(digList(item))
                    else:
                    temp.append(item)
                    return set(temp)

                    for k, v in myDict.items():
                    if type(v) is list:
                    items = digList(v)
                    for item in items:
                    invDict[item] = invDict.get(item, )
                    invDict[item].append(k)
                    else:
                    invDict[v] = invDict.get(v, )
                    invDict[v].append(k)





                    share|improve this answer


























                    • You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, ) lines

                      – gabuzo
                      Oct 24 '17 at 8:22



















                    0














                    Inverse your dictionary:



                    dict_ = {"k0":"v0", "k1":"v1", "k2":"v1"}
                    inversed_dict_ = {val: key for key, val in dict_.items()}

                    print(inversed_dict_["v1"])





                    share|improve this answer































                      0














                      As per my comment to the question. I think the easiest and one liner which works for both Python2 and Python 3 will be



                      dict(zip(inv_map.values(), inv_map.keys()))





                      share|improve this answer































                        0














                        For instance, you have the following dictionary:



                        dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}


                        And you wanna get it in such an inverted form:



                        inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}


                        First Solution. For inverting key-value pairs in your dictionary use a for-loop approach:



                        # Use this code to invert dictionaries that have non-unique values

                        inverted_dict = dictio()
                        for key, value in dict.items():
                        inverted_dict.setdefault(value, list()).append(key)


                        Second Solution. Use a dictionary comprehension approach for inversion:



                        # Use this code to invert dictionaries that have unique values

                        inverted_dict = {value: key for key, value in dict.items()}


                        Third Solution. Use reverting the inversion approach:



                        # Use this code to invert dictionaries that have lists of values

                        dict = {value: key for key in inverted_dict for value in my_map[key]}





                        share|improve this answer

































                          -1














                          Fast functional solution for non-bijective maps (values not unique):



                          from itertools import imap, groupby

                          def fst(s):
                          return s[0]

                          def snd(s):
                          return s[1]

                          def inverseDict(d):
                          """
                          input d: a -> b
                          output : b -> set(a)
                          """
                          return {
                          v : set(imap(fst, kv_iter))
                          for (v, kv_iter) in groupby(
                          sorted(d.iteritems(),
                          key=snd),
                          key=snd
                          )
                          }


                          In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.



                          Unfortunately the values have to be sortable, the sorting is required by groupby.






                          share|improve this answer


























                          • "In theory this should be faster than adding to the set (or appending to the list) one by one" - no. Given n elements in the original dict, your approach has O(n log n) time complexity due to the need to sort the dict's items, whereas the naive imperative approach has O(n) time complexity. For all I know your approach may be faster up until absurdly large dicts in practice, but it certainly isn't faster in theory.

                            – Mark Amery
                            Jul 16 '16 at 18:17





















                          -1














                          I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.



                          def dict_invert(map1):
                          inv_map = {} # new dictionary
                          for key in map1.keys():
                          inv_map[map1.get(key)] = key
                          return inv_map





                          share|improve this answer

































                            -3














                            For all kinds of dictionary, no matter if they don't have unique values to use as keys, you can create a list of keys for each value



                            inv_map = {v: inv_map.get(v, ) + [k] for k,v in my_map.items()}





                            share|improve this answer


























                            • have you tested it for non-unique values? e.g. map = { 'a': 1, 'b':2, 'c':1 } gives {1: ['c'], 2: ['b']} for inv_map, 'a' gets lost (I put inv_map = {} before your line)

                              – Matthias 009
                              May 1 '12 at 16:36






                            • 1





                              This doesn't work, because the new value of inv_map is not assigned until the comprehension completes

                              – Eric
                              Jul 30 '14 at 15:11



















                            -3














                            This is not the best solution, but it works. Let's say the dictionary we want to reverse is:



                            dictionary = {'a': 1, 'b': 2, 'c': 3}, then:



                            dictionary = {'a': 1, 'b': 2, 'c': 3}
                            reverse_dictionary = {}
                            for index, val in enumerate(list(dictionary.values())):
                            reverse_dictionary[val] = list(dictionary.keys())[index]


                            The output of reverse_dictionary, should be {1: 'a', 2: 'b', 3: 'c'}






                            share|improve this answer





























                              1 2
                              next



                              Your Answer






                              StackExchange.ifUsing("editor", function () {
                              StackExchange.using("externalEditor", function () {
                              StackExchange.using("snippets", function () {
                              StackExchange.snippets.init();
                              });
                              });
                              }, "code-snippets");

                              StackExchange.ready(function() {
                              var channelOptions = {
                              tags: "".split(" "),
                              id: "1"
                              };
                              initTagRenderer("".split(" "), "".split(" "), channelOptions);

                              StackExchange.using("externalEditor", function() {
                              // Have to fire editor after snippets, if snippets enabled
                              if (StackExchange.settings.snippets.snippetsEnabled) {
                              StackExchange.using("snippets", function() {
                              createEditor();
                              });
                              }
                              else {
                              createEditor();
                              }
                              });

                              function createEditor() {
                              StackExchange.prepareEditor({
                              heartbeatType: 'answer',
                              autoActivateHeartbeat: false,
                              convertImagesToLinks: true,
                              noModals: true,
                              showLowRepImageUploadWarning: true,
                              reputationToPostImages: 10,
                              bindNavPrevention: true,
                              postfix: "",
                              imageUploader: {
                              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                              allowUrls: true
                              },
                              onDemand: false,
                              discardSelector: ".discard-answer"
                              ,immediatelyShowMarkdownHelp:true
                              });


                              }
                              });














                              draft saved

                              draft discarded


















                              StackExchange.ready(
                              function () {
                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f483666%2fpython-reverse-invert-a-mapping%23new-answer', 'question_page');
                              }
                              );

                              Post as a guest















                              Required, but never shown




















                              StackExchange.ready(function () {
                              $("#show-editor-button input, #show-editor-button button").click(function () {
                              var showEditor = function() {
                              $("#show-editor-button").hide();
                              $("#post-form").removeClass("dno");
                              StackExchange.editor.finallyInit();
                              };

                              var useFancy = $(this).data('confirm-use-fancy');
                              if(useFancy == 'True') {
                              var popupTitle = $(this).data('confirm-fancy-title');
                              var popupBody = $(this).data('confirm-fancy-body');
                              var popupAccept = $(this).data('confirm-fancy-accept-button');

                              $(this).loadPopup({
                              url: '/post/self-answer-popup',
                              loaded: function(popup) {
                              var pTitle = $(popup).find('h2');
                              var pBody = $(popup).find('.popup-body');
                              var pSubmit = $(popup).find('.popup-submit');

                              pTitle.text(popupTitle);
                              pBody.html(popupBody);
                              pSubmit.val(popupAccept).click(showEditor);
                              }
                              })
                              } else{
                              var confirmText = $(this).data('confirm-text');
                              if (confirmText ? confirm(confirmText) : true) {
                              showEditor();
                              }
                              }
                              });
                              });






                              31 Answers
                              31






                              active

                              oldest

                              votes








                              31 Answers
                              31






                              active

                              oldest

                              votes









                              active

                              oldest

                              votes






                              active

                              oldest

                              votes








                              1 2
                              next










                              702














                              For Python 2.7.x



                              inv_map = {v: k for k, v in my_map.iteritems()}


                              For Python 3+:



                              inv_map = {v: k for k, v in my_map.items()}





                              share|improve this answer





















                              • 44





                                in python2.7+, using map.iteritems() would be more efficient.

                                – Mike Fogel
                                Dec 4 '12 at 23:40






                              • 6





                                however in python 3+ just use my_map.items() as the answer shows.

                                – Rick Teachey
                                Aug 21 '16 at 13:03






                              • 10





                                @rasen58 Python dictionaries don't have an ordering

                                – Anentropic
                                Oct 27 '16 at 12:42






                              • 4





                                This'll work except that it won't work if there is not unicity in the values. In that case you'll loose some entries

                                – gabuzo
                                Oct 23 '17 at 16:28






                              • 5





                                Fun Fact: Dictionaries will be ordered (by time of insertion) in Python 3.7 onwards.

                                – byxor
                                Jun 12 '18 at 20:18


















                              702














                              For Python 2.7.x



                              inv_map = {v: k for k, v in my_map.iteritems()}


                              For Python 3+:



                              inv_map = {v: k for k, v in my_map.items()}





                              share|improve this answer





















                              • 44





                                in python2.7+, using map.iteritems() would be more efficient.

                                – Mike Fogel
                                Dec 4 '12 at 23:40






                              • 6





                                however in python 3+ just use my_map.items() as the answer shows.

                                – Rick Teachey
                                Aug 21 '16 at 13:03






                              • 10





                                @rasen58 Python dictionaries don't have an ordering

                                – Anentropic
                                Oct 27 '16 at 12:42






                              • 4





                                This'll work except that it won't work if there is not unicity in the values. In that case you'll loose some entries

                                – gabuzo
                                Oct 23 '17 at 16:28






                              • 5





                                Fun Fact: Dictionaries will be ordered (by time of insertion) in Python 3.7 onwards.

                                – byxor
                                Jun 12 '18 at 20:18
















                              702












                              702








                              702







                              For Python 2.7.x



                              inv_map = {v: k for k, v in my_map.iteritems()}


                              For Python 3+:



                              inv_map = {v: k for k, v in my_map.items()}





                              share|improve this answer















                              For Python 2.7.x



                              inv_map = {v: k for k, v in my_map.iteritems()}


                              For Python 3+:



                              inv_map = {v: k for k, v in my_map.items()}






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Oct 14 '16 at 16:21









                              Dave Lasley

                              4,64212633




                              4,64212633










                              answered Jan 27 '09 at 15:24









                              SilentGhostSilentGhost

                              194k47266263




                              194k47266263








                              • 44





                                in python2.7+, using map.iteritems() would be more efficient.

                                – Mike Fogel
                                Dec 4 '12 at 23:40






                              • 6





                                however in python 3+ just use my_map.items() as the answer shows.

                                – Rick Teachey
                                Aug 21 '16 at 13:03






                              • 10





                                @rasen58 Python dictionaries don't have an ordering

                                – Anentropic
                                Oct 27 '16 at 12:42






                              • 4





                                This'll work except that it won't work if there is not unicity in the values. In that case you'll loose some entries

                                – gabuzo
                                Oct 23 '17 at 16:28






                              • 5





                                Fun Fact: Dictionaries will be ordered (by time of insertion) in Python 3.7 onwards.

                                – byxor
                                Jun 12 '18 at 20:18
















                              • 44





                                in python2.7+, using map.iteritems() would be more efficient.

                                – Mike Fogel
                                Dec 4 '12 at 23:40






                              • 6





                                however in python 3+ just use my_map.items() as the answer shows.

                                – Rick Teachey
                                Aug 21 '16 at 13:03






                              • 10





                                @rasen58 Python dictionaries don't have an ordering

                                – Anentropic
                                Oct 27 '16 at 12:42






                              • 4





                                This'll work except that it won't work if there is not unicity in the values. In that case you'll loose some entries

                                – gabuzo
                                Oct 23 '17 at 16:28






                              • 5





                                Fun Fact: Dictionaries will be ordered (by time of insertion) in Python 3.7 onwards.

                                – byxor
                                Jun 12 '18 at 20:18










                              44




                              44





                              in python2.7+, using map.iteritems() would be more efficient.

                              – Mike Fogel
                              Dec 4 '12 at 23:40





                              in python2.7+, using map.iteritems() would be more efficient.

                              – Mike Fogel
                              Dec 4 '12 at 23:40




                              6




                              6





                              however in python 3+ just use my_map.items() as the answer shows.

                              – Rick Teachey
                              Aug 21 '16 at 13:03





                              however in python 3+ just use my_map.items() as the answer shows.

                              – Rick Teachey
                              Aug 21 '16 at 13:03




                              10




                              10





                              @rasen58 Python dictionaries don't have an ordering

                              – Anentropic
                              Oct 27 '16 at 12:42





                              @rasen58 Python dictionaries don't have an ordering

                              – Anentropic
                              Oct 27 '16 at 12:42




                              4




                              4





                              This'll work except that it won't work if there is not unicity in the values. In that case you'll loose some entries

                              – gabuzo
                              Oct 23 '17 at 16:28





                              This'll work except that it won't work if there is not unicity in the values. In that case you'll loose some entries

                              – gabuzo
                              Oct 23 '17 at 16:28




                              5




                              5





                              Fun Fact: Dictionaries will be ordered (by time of insertion) in Python 3.7 onwards.

                              – byxor
                              Jun 12 '18 at 20:18







                              Fun Fact: Dictionaries will be ordered (by time of insertion) in Python 3.7 onwards.

                              – byxor
                              Jun 12 '18 at 20:18















                              162














                              Assuming that the values in the dict are unique:



                              dict((v, k) for k, v in my_map.iteritems())





                              share|improve this answer





















                              • 17





                                What if the values aren't unique?

                                – Buttons840
                                Apr 27 '12 at 20:34






                              • 14





                                The values have to be hashable too

                                – John La Rooy
                                May 24 '12 at 1:52






                              • 25





                                @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense.

                                – Wrzlprmft
                                Oct 25 '14 at 14:13






                              • 2





                                @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that iteritems() will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general.

                                – Evgeni Sergeev
                                Apr 21 '15 at 8:13






                              • 3





                                @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it.

                                – Leo
                                Oct 25 '16 at 19:08
















                              162














                              Assuming that the values in the dict are unique:



                              dict((v, k) for k, v in my_map.iteritems())





                              share|improve this answer





















                              • 17





                                What if the values aren't unique?

                                – Buttons840
                                Apr 27 '12 at 20:34






                              • 14





                                The values have to be hashable too

                                – John La Rooy
                                May 24 '12 at 1:52






                              • 25





                                @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense.

                                – Wrzlprmft
                                Oct 25 '14 at 14:13






                              • 2





                                @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that iteritems() will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general.

                                – Evgeni Sergeev
                                Apr 21 '15 at 8:13






                              • 3





                                @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it.

                                – Leo
                                Oct 25 '16 at 19:08














                              162












                              162








                              162







                              Assuming that the values in the dict are unique:



                              dict((v, k) for k, v in my_map.iteritems())





                              share|improve this answer















                              Assuming that the values in the dict are unique:



                              dict((v, k) for k, v in my_map.iteritems())






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 21 '16 at 12:51









                              Rick Teachey

                              15.6k73965




                              15.6k73965










                              answered Jan 27 '09 at 14:50







                              unbeknown















                              • 17





                                What if the values aren't unique?

                                – Buttons840
                                Apr 27 '12 at 20:34






                              • 14





                                The values have to be hashable too

                                – John La Rooy
                                May 24 '12 at 1:52






                              • 25





                                @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense.

                                – Wrzlprmft
                                Oct 25 '14 at 14:13






                              • 2





                                @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that iteritems() will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general.

                                – Evgeni Sergeev
                                Apr 21 '15 at 8:13






                              • 3





                                @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it.

                                – Leo
                                Oct 25 '16 at 19:08














                              • 17





                                What if the values aren't unique?

                                – Buttons840
                                Apr 27 '12 at 20:34






                              • 14





                                The values have to be hashable too

                                – John La Rooy
                                May 24 '12 at 1:52






                              • 25





                                @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense.

                                – Wrzlprmft
                                Oct 25 '14 at 14:13






                              • 2





                                @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that iteritems() will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general.

                                – Evgeni Sergeev
                                Apr 21 '15 at 8:13






                              • 3





                                @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it.

                                – Leo
                                Oct 25 '16 at 19:08








                              17




                              17





                              What if the values aren't unique?

                              – Buttons840
                              Apr 27 '12 at 20:34





                              What if the values aren't unique?

                              – Buttons840
                              Apr 27 '12 at 20:34




                              14




                              14





                              The values have to be hashable too

                              – John La Rooy
                              May 24 '12 at 1:52





                              The values have to be hashable too

                              – John La Rooy
                              May 24 '12 at 1:52




                              25




                              25





                              @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense.

                              – Wrzlprmft
                              Oct 25 '14 at 14:13





                              @Buttons840: If the values aren’t unique, there is no unique inversion of the dictionary anyway or, with other words, inverting does not make sense.

                              – Wrzlprmft
                              Oct 25 '14 at 14:13




                              2




                              2





                              @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that iteritems() will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general.

                              – Evgeni Sergeev
                              Apr 21 '15 at 8:13





                              @Buttons840 Only the last key will appear for the value. There are probably no guarantees on the order that iteritems() will output, so it may be assumed that an arbitrary key will be assigned for a non-unique value, in a way that will be apparently reproducible under some conditions, but no so in general.

                              – Evgeni Sergeev
                              Apr 21 '15 at 8:13




                              3




                              3





                              @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it.

                              – Leo
                              Oct 25 '16 at 19:08





                              @Wrzlprmft There is a natural definition for inverse in the case of non unique values. Every value is mapped to the set of keys leading to it.

                              – Leo
                              Oct 25 '16 at 19:08











                              109














                              If the values in my_map aren't unique:



                              inv_map = {}
                              for k, v in my_map.iteritems():
                              inv_map[v] = inv_map.get(v, )
                              inv_map[v].append(k)





                              share|improve this answer





















                              • 49





                                ... or just inv_map.setdefault(v, ).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit.

                                – alsuren
                                Nov 10 '10 at 14:55













                              • This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default

                                – Yaroslav Bulatov
                                Apr 22 '16 at 20:37






                              • 1





                                @YaroslavBulatov no, the code as shown here isn't broken - inv_map.get(v, ) returns the already-added list if there is one, so the assignment doesn't reset to an empty list. setdefault would still be prettier, though.

                                – Mark Amery
                                Jul 16 '16 at 17:23








                              • 8





                                A set would make more sense here. The keys are (probably) hashable, and there is no order. inv_map.setdefault(v, set()).add(k).

                                – Artyer
                                Aug 11 '17 at 17:17
















                              109














                              If the values in my_map aren't unique:



                              inv_map = {}
                              for k, v in my_map.iteritems():
                              inv_map[v] = inv_map.get(v, )
                              inv_map[v].append(k)





                              share|improve this answer





















                              • 49





                                ... or just inv_map.setdefault(v, ).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit.

                                – alsuren
                                Nov 10 '10 at 14:55













                              • This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default

                                – Yaroslav Bulatov
                                Apr 22 '16 at 20:37






                              • 1





                                @YaroslavBulatov no, the code as shown here isn't broken - inv_map.get(v, ) returns the already-added list if there is one, so the assignment doesn't reset to an empty list. setdefault would still be prettier, though.

                                – Mark Amery
                                Jul 16 '16 at 17:23








                              • 8





                                A set would make more sense here. The keys are (probably) hashable, and there is no order. inv_map.setdefault(v, set()).add(k).

                                – Artyer
                                Aug 11 '17 at 17:17














                              109












                              109








                              109







                              If the values in my_map aren't unique:



                              inv_map = {}
                              for k, v in my_map.iteritems():
                              inv_map[v] = inv_map.get(v, )
                              inv_map[v].append(k)





                              share|improve this answer















                              If the values in my_map aren't unique:



                              inv_map = {}
                              for k, v in my_map.iteritems():
                              inv_map[v] = inv_map.get(v, )
                              inv_map[v].append(k)






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 21 '16 at 12:52









                              Rick Teachey

                              15.6k73965




                              15.6k73965










                              answered Jan 27 '09 at 21:33









                              Robert RossneyRobert Rossney

                              72.1k23121199




                              72.1k23121199








                              • 49





                                ... or just inv_map.setdefault(v, ).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit.

                                – alsuren
                                Nov 10 '10 at 14:55













                              • This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default

                                – Yaroslav Bulatov
                                Apr 22 '16 at 20:37






                              • 1





                                @YaroslavBulatov no, the code as shown here isn't broken - inv_map.get(v, ) returns the already-added list if there is one, so the assignment doesn't reset to an empty list. setdefault would still be prettier, though.

                                – Mark Amery
                                Jul 16 '16 at 17:23








                              • 8





                                A set would make more sense here. The keys are (probably) hashable, and there is no order. inv_map.setdefault(v, set()).add(k).

                                – Artyer
                                Aug 11 '17 at 17:17














                              • 49





                                ... or just inv_map.setdefault(v, ).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit.

                                – alsuren
                                Nov 10 '10 at 14:55













                              • This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default

                                – Yaroslav Bulatov
                                Apr 22 '16 at 20:37






                              • 1





                                @YaroslavBulatov no, the code as shown here isn't broken - inv_map.get(v, ) returns the already-added list if there is one, so the assignment doesn't reset to an empty list. setdefault would still be prettier, though.

                                – Mark Amery
                                Jul 16 '16 at 17:23








                              • 8





                                A set would make more sense here. The keys are (probably) hashable, and there is no order. inv_map.setdefault(v, set()).add(k).

                                – Artyer
                                Aug 11 '17 at 17:17








                              49




                              49





                              ... or just inv_map.setdefault(v, ).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit.

                              – alsuren
                              Nov 10 '10 at 14:55







                              ... or just inv_map.setdefault(v, ).append(k). I used to be a defaultdict fanboy, but then I got screwed one too many times and concluded that actually explicit is better than implicit.

                              – alsuren
                              Nov 10 '10 at 14:55















                              This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default

                              – Yaroslav Bulatov
                              Apr 22 '16 at 20:37





                              This answer is incorrect for multi-map, append here is useless because the value is reset to empty list each time, should use set_default

                              – Yaroslav Bulatov
                              Apr 22 '16 at 20:37




                              1




                              1





                              @YaroslavBulatov no, the code as shown here isn't broken - inv_map.get(v, ) returns the already-added list if there is one, so the assignment doesn't reset to an empty list. setdefault would still be prettier, though.

                              – Mark Amery
                              Jul 16 '16 at 17:23







                              @YaroslavBulatov no, the code as shown here isn't broken - inv_map.get(v, ) returns the already-added list if there is one, so the assignment doesn't reset to an empty list. setdefault would still be prettier, though.

                              – Mark Amery
                              Jul 16 '16 at 17:23






                              8




                              8





                              A set would make more sense here. The keys are (probably) hashable, and there is no order. inv_map.setdefault(v, set()).add(k).

                              – Artyer
                              Aug 11 '17 at 17:17





                              A set would make more sense here. The keys are (probably) hashable, and there is no order. inv_map.setdefault(v, set()).add(k).

                              – Artyer
                              Aug 11 '17 at 17:17











                              37














                              def inverse_mapping(f):
                              return f.__class__(map(reversed, f.items()))





                              share|improve this answer



















                              • 11





                                Upvoted for retaining the type rather than silently converting into dict

                                – gerrit
                                Nov 26 '14 at 17:25






                              • 2





                                @gerrit: Too bad this motivation is not explained in the answer itself. (Moreover, the answer has to explaination at all at the moment.)

                                – vog
                                Jan 15 '17 at 21:42






                              • 1





                                This... is extremely clever. While non-human-readable, this one-liner successfully preserves both the type and ordering (e.g., for OrderedDict types) of the original dictionary by passing an anonymous iterable to the dict(iterable) form of mapping constructors. Explanatory exposition would have been helpful, of course. </sigh>

                                – Cecil Curry
                                Dec 22 '17 at 6:37








                              • 1





                                Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary.

                                – Rafael_Espericueta
                                Jun 5 '18 at 1:02
















                              37














                              def inverse_mapping(f):
                              return f.__class__(map(reversed, f.items()))





                              share|improve this answer



















                              • 11





                                Upvoted for retaining the type rather than silently converting into dict

                                – gerrit
                                Nov 26 '14 at 17:25






                              • 2





                                @gerrit: Too bad this motivation is not explained in the answer itself. (Moreover, the answer has to explaination at all at the moment.)

                                – vog
                                Jan 15 '17 at 21:42






                              • 1





                                This... is extremely clever. While non-human-readable, this one-liner successfully preserves both the type and ordering (e.g., for OrderedDict types) of the original dictionary by passing an anonymous iterable to the dict(iterable) form of mapping constructors. Explanatory exposition would have been helpful, of course. </sigh>

                                – Cecil Curry
                                Dec 22 '17 at 6:37








                              • 1





                                Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary.

                                – Rafael_Espericueta
                                Jun 5 '18 at 1:02














                              37












                              37








                              37







                              def inverse_mapping(f):
                              return f.__class__(map(reversed, f.items()))





                              share|improve this answer













                              def inverse_mapping(f):
                              return f.__class__(map(reversed, f.items()))






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered Nov 5 '09 at 10:41









                              fs.fs.

                              63858




                              63858








                              • 11





                                Upvoted for retaining the type rather than silently converting into dict

                                – gerrit
                                Nov 26 '14 at 17:25






                              • 2





                                @gerrit: Too bad this motivation is not explained in the answer itself. (Moreover, the answer has to explaination at all at the moment.)

                                – vog
                                Jan 15 '17 at 21:42






                              • 1





                                This... is extremely clever. While non-human-readable, this one-liner successfully preserves both the type and ordering (e.g., for OrderedDict types) of the original dictionary by passing an anonymous iterable to the dict(iterable) form of mapping constructors. Explanatory exposition would have been helpful, of course. </sigh>

                                – Cecil Curry
                                Dec 22 '17 at 6:37








                              • 1





                                Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary.

                                – Rafael_Espericueta
                                Jun 5 '18 at 1:02














                              • 11





                                Upvoted for retaining the type rather than silently converting into dict

                                – gerrit
                                Nov 26 '14 at 17:25






                              • 2





                                @gerrit: Too bad this motivation is not explained in the answer itself. (Moreover, the answer has to explaination at all at the moment.)

                                – vog
                                Jan 15 '17 at 21:42






                              • 1





                                This... is extremely clever. While non-human-readable, this one-liner successfully preserves both the type and ordering (e.g., for OrderedDict types) of the original dictionary by passing an anonymous iterable to the dict(iterable) form of mapping constructors. Explanatory exposition would have been helpful, of course. </sigh>

                                – Cecil Curry
                                Dec 22 '17 at 6:37








                              • 1





                                Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary.

                                – Rafael_Espericueta
                                Jun 5 '18 at 1:02








                              11




                              11





                              Upvoted for retaining the type rather than silently converting into dict

                              – gerrit
                              Nov 26 '14 at 17:25





                              Upvoted for retaining the type rather than silently converting into dict

                              – gerrit
                              Nov 26 '14 at 17:25




                              2




                              2





                              @gerrit: Too bad this motivation is not explained in the answer itself. (Moreover, the answer has to explaination at all at the moment.)

                              – vog
                              Jan 15 '17 at 21:42





                              @gerrit: Too bad this motivation is not explained in the answer itself. (Moreover, the answer has to explaination at all at the moment.)

                              – vog
                              Jan 15 '17 at 21:42




                              1




                              1





                              This... is extremely clever. While non-human-readable, this one-liner successfully preserves both the type and ordering (e.g., for OrderedDict types) of the original dictionary by passing an anonymous iterable to the dict(iterable) form of mapping constructors. Explanatory exposition would have been helpful, of course. </sigh>

                              – Cecil Curry
                              Dec 22 '17 at 6:37







                              This... is extremely clever. While non-human-readable, this one-liner successfully preserves both the type and ordering (e.g., for OrderedDict types) of the original dictionary by passing an anonymous iterable to the dict(iterable) form of mapping constructors. Explanatory exposition would have been helpful, of course. </sigh>

                              – Cecil Curry
                              Dec 22 '17 at 6:37






                              1




                              1





                              Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary.

                              – Rafael_Espericueta
                              Jun 5 '18 at 1:02





                              Clever it may be, but it doesn't work when more than one key has the same value in the original dictionary.

                              – Rafael_Espericueta
                              Jun 5 '18 at 1:02











                              30














                              Try this:



                              inv_map = dict(zip(my_map.values(), my_map.keys()))


                              (Note that the Python docs on dictionary views explicitly guarantee that .keys() and .values() have their elements in the same order, which allows the approach above to work.)



                              Alternatively:



                              inv_map = dict((my_map[k], k) for k in my_map)


                              or using python 3.0's dict comprehensions



                              inv_map = {my_map[k] : k for k in my_map}





                              share|improve this answer


























                              • Notice that this only works if the keys are unique (which is almost never the case if you want to invert them).

                                – gented
                                Jun 22 '18 at 8:26











                              • According to python.org/dev/peps/pep-0274 dict comprehensions are available in 2.7+, too.

                                – Kawu
                                Oct 27 '18 at 1:03


















                              30














                              Try this:



                              inv_map = dict(zip(my_map.values(), my_map.keys()))


                              (Note that the Python docs on dictionary views explicitly guarantee that .keys() and .values() have their elements in the same order, which allows the approach above to work.)



                              Alternatively:



                              inv_map = dict((my_map[k], k) for k in my_map)


                              or using python 3.0's dict comprehensions



                              inv_map = {my_map[k] : k for k in my_map}





                              share|improve this answer


























                              • Notice that this only works if the keys are unique (which is almost never the case if you want to invert them).

                                – gented
                                Jun 22 '18 at 8:26











                              • According to python.org/dev/peps/pep-0274 dict comprehensions are available in 2.7+, too.

                                – Kawu
                                Oct 27 '18 at 1:03
















                              30












                              30








                              30







                              Try this:



                              inv_map = dict(zip(my_map.values(), my_map.keys()))


                              (Note that the Python docs on dictionary views explicitly guarantee that .keys() and .values() have their elements in the same order, which allows the approach above to work.)



                              Alternatively:



                              inv_map = dict((my_map[k], k) for k in my_map)


                              or using python 3.0's dict comprehensions



                              inv_map = {my_map[k] : k for k in my_map}





                              share|improve this answer















                              Try this:



                              inv_map = dict(zip(my_map.values(), my_map.keys()))


                              (Note that the Python docs on dictionary views explicitly guarantee that .keys() and .values() have their elements in the same order, which allows the approach above to work.)



                              Alternatively:



                              inv_map = dict((my_map[k], k) for k in my_map)


                              or using python 3.0's dict comprehensions



                              inv_map = {my_map[k] : k for k in my_map}






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Aug 21 '16 at 12:51









                              Rick Teachey

                              15.6k73965




                              15.6k73965










                              answered Jan 27 '09 at 14:49









                              sykorasykora

                              60.1k95567




                              60.1k95567













                              • Notice that this only works if the keys are unique (which is almost never the case if you want to invert them).

                                – gented
                                Jun 22 '18 at 8:26











                              • According to python.org/dev/peps/pep-0274 dict comprehensions are available in 2.7+, too.

                                – Kawu
                                Oct 27 '18 at 1:03





















                              • Notice that this only works if the keys are unique (which is almost never the case if you want to invert them).

                                – gented
                                Jun 22 '18 at 8:26











                              • According to python.org/dev/peps/pep-0274 dict comprehensions are available in 2.7+, too.

                                – Kawu
                                Oct 27 '18 at 1:03



















                              Notice that this only works if the keys are unique (which is almost never the case if you want to invert them).

                              – gented
                              Jun 22 '18 at 8:26





                              Notice that this only works if the keys are unique (which is almost never the case if you want to invert them).

                              – gented
                              Jun 22 '18 at 8:26













                              According to python.org/dev/peps/pep-0274 dict comprehensions are available in 2.7+, too.

                              – Kawu
                              Oct 27 '18 at 1:03







                              According to python.org/dev/peps/pep-0274 dict comprehensions are available in 2.7+, too.

                              – Kawu
                              Oct 27 '18 at 1:03













                              17














                              Another, more functional, way:



                              my_map = { 'a': 1, 'b':2 }
                              dict(map(reversed, my_map.items()))





                              share|improve this answer





















                              • 2





                                Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "filter and map should die and be subsumed into list comprehensions, not grow more variants".

                                – Brian M. Hunt
                                Feb 26 '14 at 16:38






                              • 1





                                Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess)

                                – Brendan Maguire
                                Feb 26 '14 at 17:10






                              • 2





                                In Python 3 it should be my_map.items().

                                – dmvianna
                                Jul 25 '16 at 23:47






                              • 1





                                Might be less readable than others, but this way does have the benefit of being able to swap out dict with other mapping types such as collections.OrderedDict or collections.defaultdict

                                – Will S
                                Aug 17 '17 at 9:51


















                              17














                              Another, more functional, way:



                              my_map = { 'a': 1, 'b':2 }
                              dict(map(reversed, my_map.items()))





                              share|improve this answer





















                              • 2





                                Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "filter and map should die and be subsumed into list comprehensions, not grow more variants".

                                – Brian M. Hunt
                                Feb 26 '14 at 16:38






                              • 1





                                Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess)

                                – Brendan Maguire
                                Feb 26 '14 at 17:10






                              • 2





                                In Python 3 it should be my_map.items().

                                – dmvianna
                                Jul 25 '16 at 23:47






                              • 1





                                Might be less readable than others, but this way does have the benefit of being able to swap out dict with other mapping types such as collections.OrderedDict or collections.defaultdict

                                – Will S
                                Aug 17 '17 at 9:51
















                              17












                              17








                              17







                              Another, more functional, way:



                              my_map = { 'a': 1, 'b':2 }
                              dict(map(reversed, my_map.items()))





                              share|improve this answer















                              Another, more functional, way:



                              my_map = { 'a': 1, 'b':2 }
                              dict(map(reversed, my_map.items()))






                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Jan 5 '17 at 14:51

























                              answered Feb 26 '14 at 16:35









                              Brendan MaguireBrendan Maguire

                              1,74421523




                              1,74421523








                              • 2





                                Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "filter and map should die and be subsumed into list comprehensions, not grow more variants".

                                – Brian M. Hunt
                                Feb 26 '14 at 16:38






                              • 1





                                Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess)

                                – Brendan Maguire
                                Feb 26 '14 at 17:10






                              • 2





                                In Python 3 it should be my_map.items().

                                – dmvianna
                                Jul 25 '16 at 23:47






                              • 1





                                Might be less readable than others, but this way does have the benefit of being able to swap out dict with other mapping types such as collections.OrderedDict or collections.defaultdict

                                – Will S
                                Aug 17 '17 at 9:51
















                              • 2





                                Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "filter and map should die and be subsumed into list comprehensions, not grow more variants".

                                – Brian M. Hunt
                                Feb 26 '14 at 16:38






                              • 1





                                Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess)

                                – Brendan Maguire
                                Feb 26 '14 at 17:10






                              • 2





                                In Python 3 it should be my_map.items().

                                – dmvianna
                                Jul 25 '16 at 23:47






                              • 1





                                Might be less readable than others, but this way does have the benefit of being able to swap out dict with other mapping types such as collections.OrderedDict or collections.defaultdict

                                – Will S
                                Aug 17 '17 at 9:51










                              2




                              2





                              Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "filter and map should die and be subsumed into list comprehensions, not grow more variants".

                              – Brian M. Hunt
                              Feb 26 '14 at 16:38





                              Thanks for posting. I am not sure this is preferable - to quote Guido Van Rossum in PEP 279: "filter and map should die and be subsumed into list comprehensions, not grow more variants".

                              – Brian M. Hunt
                              Feb 26 '14 at 16:38




                              1




                              1





                              Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess)

                              – Brendan Maguire
                              Feb 26 '14 at 17:10





                              Yeah, that's a fair point Brian. I was just adding it as a point of conversation. The dict comprehension way is more readable for most I'd imagine. (And likely faster too I'd guess)

                              – Brendan Maguire
                              Feb 26 '14 at 17:10




                              2




                              2





                              In Python 3 it should be my_map.items().

                              – dmvianna
                              Jul 25 '16 at 23:47





                              In Python 3 it should be my_map.items().

                              – dmvianna
                              Jul 25 '16 at 23:47




                              1




                              1





                              Might be less readable than others, but this way does have the benefit of being able to swap out dict with other mapping types such as collections.OrderedDict or collections.defaultdict

                              – Will S
                              Aug 17 '17 at 9:51







                              Might be less readable than others, but this way does have the benefit of being able to swap out dict with other mapping types such as collections.OrderedDict or collections.defaultdict

                              – Will S
                              Aug 17 '17 at 9:51













                              7














                              This expands upon the answer Python reverse / invert a mapping, applying to when the values in the dict aren't unique.



                              class ReversibleDict(dict):

                              def reversed(self):
                              """
                              Return a reversed dict, with common values in the original dict
                              grouped into a list in the returned dict.

                              Example:
                              >>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
                              >>> d.reversed()
                              {1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
                              """

                              revdict = {}
                              for k, v in self.iteritems():
                              revdict.setdefault(v, ).append(k)
                              return revdict


                              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 a list, and there are applications for which this makes sense, instead of setdefault(v, ).append(k), use setdefault(v, set()).add(k).






                              share|improve this answer


























                              • this would also be a good place to use sets instead of lists, i.e. revdict.setdefault(v, set()).add(k)

                                – mueslo
                                Dec 22 '16 at 20:42











                              • Of course, but that's exacty why it's a good reason to use set. It's the intrinsic type that applies here. What if I want to find all keys where the values are not 1 or 2? Then I can just do d.keys() - inv_d[1] - inv_d[2] (in Python 3)

                                – mueslo
                                Dec 22 '16 at 20:57
















                              7














                              This expands upon the answer Python reverse / invert a mapping, applying to when the values in the dict aren't unique.



                              class ReversibleDict(dict):

                              def reversed(self):
                              """
                              Return a reversed dict, with common values in the original dict
                              grouped into a list in the returned dict.

                              Example:
                              >>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
                              >>> d.reversed()
                              {1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
                              """

                              revdict = {}
                              for k, v in self.iteritems():
                              revdict.setdefault(v, ).append(k)
                              return revdict


                              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 a list, and there are applications for which this makes sense, instead of setdefault(v, ).append(k), use setdefault(v, set()).add(k).






                              share|improve this answer


























                              • this would also be a good place to use sets instead of lists, i.e. revdict.setdefault(v, set()).add(k)

                                – mueslo
                                Dec 22 '16 at 20:42











                              • Of course, but that's exacty why it's a good reason to use set. It's the intrinsic type that applies here. What if I want to find all keys where the values are not 1 or 2? Then I can just do d.keys() - inv_d[1] - inv_d[2] (in Python 3)

                                – mueslo
                                Dec 22 '16 at 20:57














                              7












                              7








                              7







                              This expands upon the answer Python reverse / invert a mapping, applying to when the values in the dict aren't unique.



                              class ReversibleDict(dict):

                              def reversed(self):
                              """
                              Return a reversed dict, with common values in the original dict
                              grouped into a list in the returned dict.

                              Example:
                              >>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
                              >>> d.reversed()
                              {1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
                              """

                              revdict = {}
                              for k, v in self.iteritems():
                              revdict.setdefault(v, ).append(k)
                              return revdict


                              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 a list, and there are applications for which this makes sense, instead of setdefault(v, ).append(k), use setdefault(v, set()).add(k).






                              share|improve this answer















                              This expands upon the answer Python reverse / invert a mapping, applying to when the values in the dict aren't unique.



                              class ReversibleDict(dict):

                              def reversed(self):
                              """
                              Return a reversed dict, with common values in the original dict
                              grouped into a list in the returned dict.

                              Example:
                              >>> d = ReversibleDict({'a': 3, 'c': 2, 'b': 2, 'e': 3, 'd': 1, 'f': 2})
                              >>> d.reversed()
                              {1: ['d'], 2: ['c', 'b', 'f'], 3: ['a', 'e']}
                              """

                              revdict = {}
                              for k, v in self.iteritems():
                              revdict.setdefault(v, ).append(k)
                              return revdict


                              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 a list, and there are applications for which this makes sense, instead of setdefault(v, ).append(k), use setdefault(v, set()).add(k).







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited May 23 '17 at 11:54









                              Community

                              11




                              11










                              answered Oct 24 '12 at 20:40









                              A-B-BA-B-B

                              23.3k66369




                              23.3k66369













                              • this would also be a good place to use sets instead of lists, i.e. revdict.setdefault(v, set()).add(k)

                                – mueslo
                                Dec 22 '16 at 20:42











                              • Of course, but that's exacty why it's a good reason to use set. It's the intrinsic type that applies here. What if I want to find all keys where the values are not 1 or 2? Then I can just do d.keys() - inv_d[1] - inv_d[2] (in Python 3)

                                – mueslo
                                Dec 22 '16 at 20:57



















                              • this would also be a good place to use sets instead of lists, i.e. revdict.setdefault(v, set()).add(k)

                                – mueslo
                                Dec 22 '16 at 20:42











                              • Of course, but that's exacty why it's a good reason to use set. It's the intrinsic type that applies here. What if I want to find all keys where the values are not 1 or 2? Then I can just do d.keys() - inv_d[1] - inv_d[2] (in Python 3)

                                – mueslo
                                Dec 22 '16 at 20:57

















                              this would also be a good place to use sets instead of lists, i.e. revdict.setdefault(v, set()).add(k)

                              – mueslo
                              Dec 22 '16 at 20:42





                              this would also be a good place to use sets instead of lists, i.e. revdict.setdefault(v, set()).add(k)

                              – mueslo
                              Dec 22 '16 at 20:42













                              Of course, but that's exacty why it's a good reason to use set. It's the intrinsic type that applies here. What if I want to find all keys where the values are not 1 or 2? Then I can just do d.keys() - inv_d[1] - inv_d[2] (in Python 3)

                              – mueslo
                              Dec 22 '16 at 20:57





                              Of course, but that's exacty why it's a good reason to use set. It's the intrinsic type that applies here. What if I want to find all keys where the values are not 1 or 2? Then I can just do d.keys() - inv_d[1] - inv_d[2] (in Python 3)

                              – mueslo
                              Dec 22 '16 at 20:57











                              6














                              Combination of list and dictionary comprehension. Can handle duplicate keys



                              {v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}





                              share|improve this answer






























                                6














                                Combination of list and dictionary comprehension. Can handle duplicate keys



                                {v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}





                                share|improve this answer




























                                  6












                                  6








                                  6







                                  Combination of list and dictionary comprehension. Can handle duplicate keys



                                  {v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}





                                  share|improve this answer















                                  Combination of list and dictionary comprehension. Can handle duplicate keys



                                  {v:[i for i in d.keys() if d[i] == v ] for k,v in d.items()}






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Apr 19 '18 at 3:28







                                  user6655984

















                                  answered Apr 19 '18 at 3:24









                                  SVJSVJ

                                  6112




                                  6112























                                      5














                                      Adding my 2 cents of pythonic way:



                                      inv_map = dict(map(reversed, my_map.items()))


                                      Example:



                                      In [7]: my_map
                                      Out[7]: {1: 'one', 2: 'two', 3: 'three'}

                                      In [8]: inv_map = dict(map(reversed, my_map.items()))

                                      In [9]: inv_map
                                      Out[9]: {'one': 1, 'three': 3, 'two': 2}





                                      share|improve this answer
























                                      • This is a clone of Brendan Maguire's answer which has been given three years before.

                                        – Adrian W
                                        Sep 20 '18 at 10:01
















                                      5














                                      Adding my 2 cents of pythonic way:



                                      inv_map = dict(map(reversed, my_map.items()))


                                      Example:



                                      In [7]: my_map
                                      Out[7]: {1: 'one', 2: 'two', 3: 'three'}

                                      In [8]: inv_map = dict(map(reversed, my_map.items()))

                                      In [9]: inv_map
                                      Out[9]: {'one': 1, 'three': 3, 'two': 2}





                                      share|improve this answer
























                                      • This is a clone of Brendan Maguire's answer which has been given three years before.

                                        – Adrian W
                                        Sep 20 '18 at 10:01














                                      5












                                      5








                                      5







                                      Adding my 2 cents of pythonic way:



                                      inv_map = dict(map(reversed, my_map.items()))


                                      Example:



                                      In [7]: my_map
                                      Out[7]: {1: 'one', 2: 'two', 3: 'three'}

                                      In [8]: inv_map = dict(map(reversed, my_map.items()))

                                      In [9]: inv_map
                                      Out[9]: {'one': 1, 'three': 3, 'two': 2}





                                      share|improve this answer













                                      Adding my 2 cents of pythonic way:



                                      inv_map = dict(map(reversed, my_map.items()))


                                      Example:



                                      In [7]: my_map
                                      Out[7]: {1: 'one', 2: 'two', 3: 'three'}

                                      In [8]: inv_map = dict(map(reversed, my_map.items()))

                                      In [9]: inv_map
                                      Out[9]: {'one': 1, 'three': 3, 'two': 2}






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Apr 3 '17 at 5:39









                                      Amit KushwahaAmit Kushwaha

                                      1,0741011




                                      1,0741011













                                      • This is a clone of Brendan Maguire's answer which has been given three years before.

                                        – Adrian W
                                        Sep 20 '18 at 10:01



















                                      • This is a clone of Brendan Maguire's answer which has been given three years before.

                                        – Adrian W
                                        Sep 20 '18 at 10:01

















                                      This is a clone of Brendan Maguire's answer which has been given three years before.

                                      – Adrian W
                                      Sep 20 '18 at 10:01





                                      This is a clone of Brendan Maguire's answer which has been given three years before.

                                      – Adrian W
                                      Sep 20 '18 at 10:01











                                      4














                                      If the values aren't unique, and you're a little hardcore:



                                      inv_map = dict(
                                      (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())])
                                      for v in set(my_map.values())
                                      )


                                      Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over items() multiple times.






                                      share|improve this answer





















                                      • 5





                                        This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion.

                                        – Russ Bradberry
                                        Oct 3 '12 at 19:19
















                                      4














                                      If the values aren't unique, and you're a little hardcore:



                                      inv_map = dict(
                                      (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())])
                                      for v in set(my_map.values())
                                      )


                                      Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over items() multiple times.






                                      share|improve this answer





















                                      • 5





                                        This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion.

                                        – Russ Bradberry
                                        Oct 3 '12 at 19:19














                                      4












                                      4








                                      4







                                      If the values aren't unique, and you're a little hardcore:



                                      inv_map = dict(
                                      (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())])
                                      for v in set(my_map.values())
                                      )


                                      Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over items() multiple times.






                                      share|improve this answer















                                      If the values aren't unique, and you're a little hardcore:



                                      inv_map = dict(
                                      (v, [k for (k, xx) in filter(lambda (key, value): value == v, my_map.items())])
                                      for v in set(my_map.values())
                                      )


                                      Especially for a large dict, note that this solution is far less efficient than the answer Python reverse / invert a mapping because it loops over items() multiple times.







                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited May 23 '17 at 12:34









                                      Community

                                      11




                                      11










                                      answered Apr 17 '10 at 20:14









                                      pcvpcv

                                      1,3711520




                                      1,3711520








                                      • 5





                                        This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion.

                                        – Russ Bradberry
                                        Oct 3 '12 at 19:19














                                      • 5





                                        This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion.

                                        – Russ Bradberry
                                        Oct 3 '12 at 19:19








                                      5




                                      5





                                      This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion.

                                      – Russ Bradberry
                                      Oct 3 '12 at 19:19





                                      This is just plain unreadable and a good example of how to not write maintainable code. I won't -1 because it still answers the question, just my opinion.

                                      – Russ Bradberry
                                      Oct 3 '12 at 19:19











                                      4














                                      We may also reverse a dictionary with duplicate keys using defaultdict:



                                      from collections import Counter, defaultdict

                                      def invert_dict(d):
                                      d_inv = defaultdict(list)
                                      for k, v in c.items():
                                      d_inv[v].append(k)
                                      return d_inv

                                      text = 'aaa bbb ccc ddd aaa bbb ccc aaa'
                                      c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1})
                                      dict(invert_dict(c)) # {1: ['ddd'], 2: ['bbb', 'ccc'], 3: ['aaa']}


                                      See here:




                                      This technique is simpler and faster than an equivalent technique using dict.setdefault().







                                      share|improve this answer






























                                        4














                                        We may also reverse a dictionary with duplicate keys using defaultdict:



                                        from collections import Counter, defaultdict

                                        def invert_dict(d):
                                        d_inv = defaultdict(list)
                                        for k, v in c.items():
                                        d_inv[v].append(k)
                                        return d_inv

                                        text = 'aaa bbb ccc ddd aaa bbb ccc aaa'
                                        c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1})
                                        dict(invert_dict(c)) # {1: ['ddd'], 2: ['bbb', 'ccc'], 3: ['aaa']}


                                        See here:




                                        This technique is simpler and faster than an equivalent technique using dict.setdefault().







                                        share|improve this answer




























                                          4












                                          4








                                          4







                                          We may also reverse a dictionary with duplicate keys using defaultdict:



                                          from collections import Counter, defaultdict

                                          def invert_dict(d):
                                          d_inv = defaultdict(list)
                                          for k, v in c.items():
                                          d_inv[v].append(k)
                                          return d_inv

                                          text = 'aaa bbb ccc ddd aaa bbb ccc aaa'
                                          c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1})
                                          dict(invert_dict(c)) # {1: ['ddd'], 2: ['bbb', 'ccc'], 3: ['aaa']}


                                          See here:




                                          This technique is simpler and faster than an equivalent technique using dict.setdefault().







                                          share|improve this answer















                                          We may also reverse a dictionary with duplicate keys using defaultdict:



                                          from collections import Counter, defaultdict

                                          def invert_dict(d):
                                          d_inv = defaultdict(list)
                                          for k, v in c.items():
                                          d_inv[v].append(k)
                                          return d_inv

                                          text = 'aaa bbb ccc ddd aaa bbb ccc aaa'
                                          c = Counter(text.split()) # Counter({'aaa': 3, 'bbb': 2, 'ccc': 2, 'ddd': 1})
                                          dict(invert_dict(c)) # {1: ['ddd'], 2: ['bbb', 'ccc'], 3: ['aaa']}


                                          See here:




                                          This technique is simpler and faster than an equivalent technique using dict.setdefault().








                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Dec 26 '16 at 23:14

























                                          answered Dec 26 '16 at 23:01









                                          irudyakirudyak

                                          76269




                                          76269























                                              3














                                              In addition to the other functions suggested above, if you like lambdas:



                                              invert = lambda mydict: {v:k for k, v in mydict.items()}


                                              Or, you could do it this way too:



                                              invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )





                                              share|improve this answer


























                                              • -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a PEP 8 violation.

                                                – Mark Amery
                                                Jul 16 '16 at 18:03
















                                              3














                                              In addition to the other functions suggested above, if you like lambdas:



                                              invert = lambda mydict: {v:k for k, v in mydict.items()}


                                              Or, you could do it this way too:



                                              invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )





                                              share|improve this answer


























                                              • -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a PEP 8 violation.

                                                – Mark Amery
                                                Jul 16 '16 at 18:03














                                              3












                                              3








                                              3







                                              In addition to the other functions suggested above, if you like lambdas:



                                              invert = lambda mydict: {v:k for k, v in mydict.items()}


                                              Or, you could do it this way too:



                                              invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )





                                              share|improve this answer















                                              In addition to the other functions suggested above, if you like lambdas:



                                              invert = lambda mydict: {v:k for k, v in mydict.items()}


                                              Or, you could do it this way too:



                                              invert = lambda mydict: dict( zip(mydict.values(), mydict.keys()) )






                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Mar 8 '14 at 21:28

























                                              answered Apr 9 '13 at 19:20









                                              RussellStewartRussellStewart

                                              3,95512022




                                              3,95512022













                                              • -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a PEP 8 violation.

                                                – Mark Amery
                                                Jul 16 '16 at 18:03



















                                              • -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a PEP 8 violation.

                                                – Mark Amery
                                                Jul 16 '16 at 18:03

















                                              -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a PEP 8 violation.

                                              – Mark Amery
                                              Jul 16 '16 at 18:03





                                              -1; all you've done is taken other answers from the page and put them into a lambda. Also, assigning a lambda to a variable is a PEP 8 violation.

                                              – Mark Amery
                                              Jul 16 '16 at 18:03











                                              3














                                              This handles non-unique values and retains much of the look of the unique case.



                                              inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}


                                              For Python 3.x, replace itervalues with values.
                                              I can't take credit for this... it was suggested by Icon Jack.






                                              share|improve this answer


























                                              • This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one.

                                                – gabuzo
                                                Oct 24 '17 at 8:21











                                              • Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data.

                                                – Ersatz Kwisatz
                                                Oct 25 '17 at 17:01
















                                              3














                                              This handles non-unique values and retains much of the look of the unique case.



                                              inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}


                                              For Python 3.x, replace itervalues with values.
                                              I can't take credit for this... it was suggested by Icon Jack.






                                              share|improve this answer


























                                              • This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one.

                                                – gabuzo
                                                Oct 24 '17 at 8:21











                                              • Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data.

                                                – Ersatz Kwisatz
                                                Oct 25 '17 at 17:01














                                              3












                                              3








                                              3







                                              This handles non-unique values and retains much of the look of the unique case.



                                              inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}


                                              For Python 3.x, replace itervalues with values.
                                              I can't take credit for this... it was suggested by Icon Jack.






                                              share|improve this answer















                                              This handles non-unique values and retains much of the look of the unique case.



                                              inv_map = {v:[k for k in my_map if my_map[k] == v] for v in my_map.itervalues()}


                                              For Python 3.x, replace itervalues with values.
                                              I can't take credit for this... it was suggested by Icon Jack.







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Jan 25 '17 at 20:29









                                              miken32

                                              23.8k84972




                                              23.8k84972










                                              answered Jan 25 '17 at 20:23









                                              Ersatz KwisatzErsatz Kwisatz

                                              413




                                              413













                                              • This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one.

                                                – gabuzo
                                                Oct 24 '17 at 8:21











                                              • Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data.

                                                – Ersatz Kwisatz
                                                Oct 25 '17 at 17:01



















                                              • This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one.

                                                – gabuzo
                                                Oct 24 '17 at 8:21











                                              • Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data.

                                                – Ersatz Kwisatz
                                                Oct 25 '17 at 17:01

















                                              This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one.

                                              – gabuzo
                                              Oct 24 '17 at 8:21





                                              This solution is quite elegant as a one liner and it manages the non unique values case. However it has a complexity in O(n2) which means it should be ok for several dozens of elements but it would be too slow for practical use if you have several hundreds of thousands of elements in your initial dictionary. The solutions based on a default dict are way faster than this one.

                                              – gabuzo
                                              Oct 24 '17 at 8:21













                                              Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data.

                                              – Ersatz Kwisatz
                                              Oct 25 '17 at 17:01





                                              Gabuzo is quite right. This version is (arguably) clearer than some, but it is not suitable for large data.

                                              – Ersatz Kwisatz
                                              Oct 25 '17 at 17:01











                                              2














                                              I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":



                                              class SymDict:
                                              def __init__(self):
                                              self.aToB = {}
                                              self.bToA = {}

                                              def assocAB(self, a, b):
                                              # Stores and returns a tuple (a,b) of overwritten bindings
                                              currB = None
                                              if a in self.aToB: currB = self.bToA[a]
                                              currA = None
                                              if b in self.bToA: currA = self.aToB[b]

                                              self.aToB[a] = b
                                              self.bToA[b] = a
                                              return (currA, currB)

                                              def lookupA(self, a):
                                              if a in self.aToB:
                                              return self.aToB[a]
                                              return None

                                              def lookupB(self, b):
                                              if b in self.bToA:
                                              return self.bToA[b]
                                              return None


                                              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.






                                              share|improve this answer


























                                              • I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators.

                                                – Brian M. Hunt
                                                Sep 28 '14 at 10:59











                                              • @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions...

                                                – NcAdams
                                                Sep 28 '14 at 20:46













                                              • And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later

                                                – NcAdams
                                                Sep 28 '14 at 20:47








                                              • 1





                                                "This implementation is way more efficient than inverting an entire dictionary" - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be slower than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling dictresize, but this approach denies Python that possibility.

                                                – Mark Amery
                                                Jul 16 '16 at 18:11
















                                              2














                                              I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":



                                              class SymDict:
                                              def __init__(self):
                                              self.aToB = {}
                                              self.bToA = {}

                                              def assocAB(self, a, b):
                                              # Stores and returns a tuple (a,b) of overwritten bindings
                                              currB = None
                                              if a in self.aToB: currB = self.bToA[a]
                                              currA = None
                                              if b in self.bToA: currA = self.aToB[b]

                                              self.aToB[a] = b
                                              self.bToA[b] = a
                                              return (currA, currB)

                                              def lookupA(self, a):
                                              if a in self.aToB:
                                              return self.aToB[a]
                                              return None

                                              def lookupB(self, b):
                                              if b in self.bToA:
                                              return self.bToA[b]
                                              return None


                                              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.






                                              share|improve this answer


























                                              • I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators.

                                                – Brian M. Hunt
                                                Sep 28 '14 at 10:59











                                              • @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions...

                                                – NcAdams
                                                Sep 28 '14 at 20:46













                                              • And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later

                                                – NcAdams
                                                Sep 28 '14 at 20:47








                                              • 1





                                                "This implementation is way more efficient than inverting an entire dictionary" - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be slower than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling dictresize, but this approach denies Python that possibility.

                                                – Mark Amery
                                                Jul 16 '16 at 18:11














                                              2












                                              2








                                              2







                                              I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":



                                              class SymDict:
                                              def __init__(self):
                                              self.aToB = {}
                                              self.bToA = {}

                                              def assocAB(self, a, b):
                                              # Stores and returns a tuple (a,b) of overwritten bindings
                                              currB = None
                                              if a in self.aToB: currB = self.bToA[a]
                                              currA = None
                                              if b in self.bToA: currA = self.aToB[b]

                                              self.aToB[a] = b
                                              self.bToA[b] = a
                                              return (currA, currB)

                                              def lookupA(self, a):
                                              if a in self.aToB:
                                              return self.aToB[a]
                                              return None

                                              def lookupB(self, b):
                                              if b in self.bToA:
                                              return self.bToA[b]
                                              return None


                                              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.






                                              share|improve this answer















                                              I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":



                                              class SymDict:
                                              def __init__(self):
                                              self.aToB = {}
                                              self.bToA = {}

                                              def assocAB(self, a, b):
                                              # Stores and returns a tuple (a,b) of overwritten bindings
                                              currB = None
                                              if a in self.aToB: currB = self.bToA[a]
                                              currA = None
                                              if b in self.bToA: currA = self.aToB[b]

                                              self.aToB[a] = b
                                              self.bToA[b] = a
                                              return (currA, currB)

                                              def lookupA(self, a):
                                              if a in self.aToB:
                                              return self.aToB[a]
                                              return None

                                              def lookupB(self, b):
                                              if b in self.bToA:
                                              return self.bToA[b]
                                              return None


                                              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.







                                              share|improve this answer














                                              share|improve this answer



                                              share|improve this answer








                                              edited Sep 28 '14 at 7:18

























                                              answered Sep 28 '14 at 6:50









                                              NcAdamsNcAdams

                                              80531225




                                              80531225













                                              • I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators.

                                                – Brian M. Hunt
                                                Sep 28 '14 at 10:59











                                              • @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions...

                                                – NcAdams
                                                Sep 28 '14 at 20:46













                                              • And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later

                                                – NcAdams
                                                Sep 28 '14 at 20:47








                                              • 1





                                                "This implementation is way more efficient than inverting an entire dictionary" - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be slower than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling dictresize, but this approach denies Python that possibility.

                                                – Mark Amery
                                                Jul 16 '16 at 18:11



















                                              • I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators.

                                                – Brian M. Hunt
                                                Sep 28 '14 at 10:59











                                              • @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions...

                                                – NcAdams
                                                Sep 28 '14 at 20:46













                                              • And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later

                                                – NcAdams
                                                Sep 28 '14 at 20:47








                                              • 1





                                                "This implementation is way more efficient than inverting an entire dictionary" - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be slower than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling dictresize, but this approach denies Python that possibility.

                                                – Mark Amery
                                                Jul 16 '16 at 18:11

















                                              I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators.

                                              – Brian M. Hunt
                                              Sep 28 '14 at 10:59





                                              I like this idea, though it would be good to note that it trades off additional memory to achieve improved computation. A happier medium may be caching or lazily computing the mirror. It is also worth noting that it could be made more syntactically appealing with e.g. dictionary views and custom operators.

                                              – Brian M. Hunt
                                              Sep 28 '14 at 10:59













                                              @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions...

                                              – NcAdams
                                              Sep 28 '14 at 20:46







                                              @BrianM.Hunt It trades off memory, but not a lot. You only store two sets of pointers to each object. If your objects are much bigger than single integers, this won't make much of a difference. If you have huge table of tiny objects on the other hand, you might need to consider those suggestions...

                                              – NcAdams
                                              Sep 28 '14 at 20:46















                                              And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later

                                              – NcAdams
                                              Sep 28 '14 at 20:47







                                              And I agree, there's more to be done here -- I might flesh this out into a fully functioning datatype later

                                              – NcAdams
                                              Sep 28 '14 at 20:47






                                              1




                                              1





                                              "This implementation is way more efficient than inverting an entire dictionary" - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be slower than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling dictresize, but this approach denies Python that possibility.

                                              – Mark Amery
                                              Jul 16 '16 at 18:11





                                              "This implementation is way more efficient than inverting an entire dictionary" - um, why? I don't see any plausible way this approach can have a significant performance benefit; you've still got two dictionaries this way. If anything, I'd expect this to be slower than, say, inverting the dict with a comprehension, because if you invert the dict Python can plausibly know in advance how many buckets to allocate in the underlying C data structure and create the inverse map without ever calling dictresize, but this approach denies Python that possibility.

                                              – Mark Amery
                                              Jul 16 '16 at 18:11











                                              2














                                              Using zip



                                              inv_map = dict(zip(my_map.values(), my_map.keys()))





                                              share|improve this answer




























                                                2














                                                Using zip



                                                inv_map = dict(zip(my_map.values(), my_map.keys()))





                                                share|improve this answer


























                                                  2












                                                  2








                                                  2







                                                  Using zip



                                                  inv_map = dict(zip(my_map.values(), my_map.keys()))





                                                  share|improve this answer













                                                  Using zip



                                                  inv_map = dict(zip(my_map.values(), my_map.keys()))






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Sep 11 '16 at 22:26









                                                  Kwaw AnnorKwaw Annor

                                                  9441010




                                                  9441010























                                                      1














                                                      Try this for python 2.7/3.x



                                                      inv_map={};
                                                      for i in my_map:
                                                      inv_map[my_map[i]]=i
                                                      print inv_map





                                                      share|improve this answer






























                                                        1














                                                        Try this for python 2.7/3.x



                                                        inv_map={};
                                                        for i in my_map:
                                                        inv_map[my_map[i]]=i
                                                        print inv_map





                                                        share|improve this answer




























                                                          1












                                                          1








                                                          1







                                                          Try this for python 2.7/3.x



                                                          inv_map={};
                                                          for i in my_map:
                                                          inv_map[my_map[i]]=i
                                                          print inv_map





                                                          share|improve this answer















                                                          Try this for python 2.7/3.x



                                                          inv_map={};
                                                          for i in my_map:
                                                          inv_map[my_map[i]]=i
                                                          print inv_map






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Aug 21 '16 at 12:56









                                                          Rick Teachey

                                                          15.6k73965




                                                          15.6k73965










                                                          answered Jul 25 '14 at 9:31









                                                          dhvlnykdhvlnyk

                                                          77111




                                                          77111























                                                              1














                                                              I would do it that way in python 2.



                                                              inv_map = {my_map[x] : x for x in my_map}





                                                              share|improve this answer






























                                                                1














                                                                I would do it that way in python 2.



                                                                inv_map = {my_map[x] : x for x in my_map}





                                                                share|improve this answer




























                                                                  1












                                                                  1








                                                                  1







                                                                  I would do it that way in python 2.



                                                                  inv_map = {my_map[x] : x for x in my_map}





                                                                  share|improve this answer















                                                                  I would do it that way in python 2.



                                                                  inv_map = {my_map[x] : x for x in my_map}






                                                                  share|improve this answer














                                                                  share|improve this answer



                                                                  share|improve this answer








                                                                  edited Aug 2 '17 at 22:24









                                                                  Cedar

                                                                  6112




                                                                  6112










                                                                  answered Apr 26 '17 at 14:28









                                                                  genghiscradegenghiscrade

                                                                  111




                                                                  111























                                                                      1














                                                                      def invertDictionary(d):
                                                                      myDict = {}
                                                                      for i in d:
                                                                      value = d.get(i)
                                                                      myDict.setdefault(value,).append(i)
                                                                      return myDict
                                                                      print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})


                                                                      This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}






                                                                      share|improve this answer




























                                                                        1














                                                                        def invertDictionary(d):
                                                                        myDict = {}
                                                                        for i in d:
                                                                        value = d.get(i)
                                                                        myDict.setdefault(value,).append(i)
                                                                        return myDict
                                                                        print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})


                                                                        This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}






                                                                        share|improve this answer


























                                                                          1












                                                                          1








                                                                          1







                                                                          def invertDictionary(d):
                                                                          myDict = {}
                                                                          for i in d:
                                                                          value = d.get(i)
                                                                          myDict.setdefault(value,).append(i)
                                                                          return myDict
                                                                          print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})


                                                                          This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}






                                                                          share|improve this answer













                                                                          def invertDictionary(d):
                                                                          myDict = {}
                                                                          for i in d:
                                                                          value = d.get(i)
                                                                          myDict.setdefault(value,).append(i)
                                                                          return myDict
                                                                          print invertDictionary({'a':1, 'b':2, 'c':3 , 'd' : 1})


                                                                          This will provide output as : {1: ['a', 'd'], 2: ['b'], 3: ['c']}







                                                                          share|improve this answer












                                                                          share|improve this answer



                                                                          share|improve this answer










                                                                          answered Aug 30 '17 at 10:11









                                                                          RVRRVR

                                                                          30239




                                                                          30239























                                                                              1














                                                                                def reverse_dictionary(input_dict):
                                                                              out = {}
                                                                              for v in input_dict.values():
                                                                              for value in v:
                                                                              if value not in out:
                                                                              out[value.lower()] =

                                                                              for i in input_dict:
                                                                              for j in out:
                                                                              if j in map (lambda x : x.lower(),input_dict[i]):
                                                                              out[j].append(i.lower())
                                                                              out[j].sort()
                                                                              return out


                                                                              this code do like this:



                                                                              r = reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})

                                                                              print(r)

                                                                              {'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}





                                                                              share|improve this answer


























                                                                              • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

                                                                                – Tom Aranda
                                                                                Dec 18 '17 at 16:17











                                                                              • It is a nice solution

                                                                                – Dr Beco
                                                                                Jul 14 '18 at 16:06











                                                                              • It's very nice, but a lot of unexplained decisions (for example, why lower case for keys?)

                                                                                – Liudvikas Akelis
                                                                                Sep 7 '18 at 12:49
















                                                                              1














                                                                                def reverse_dictionary(input_dict):
                                                                              out = {}
                                                                              for v in input_dict.values():
                                                                              for value in v:
                                                                              if value not in out:
                                                                              out[value.lower()] =

                                                                              for i in input_dict:
                                                                              for j in out:
                                                                              if j in map (lambda x : x.lower(),input_dict[i]):
                                                                              out[j].append(i.lower())
                                                                              out[j].sort()
                                                                              return out


                                                                              this code do like this:



                                                                              r = reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})

                                                                              print(r)

                                                                              {'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}





                                                                              share|improve this answer


























                                                                              • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

                                                                                – Tom Aranda
                                                                                Dec 18 '17 at 16:17











                                                                              • It is a nice solution

                                                                                – Dr Beco
                                                                                Jul 14 '18 at 16:06











                                                                              • It's very nice, but a lot of unexplained decisions (for example, why lower case for keys?)

                                                                                – Liudvikas Akelis
                                                                                Sep 7 '18 at 12:49














                                                                              1












                                                                              1








                                                                              1







                                                                                def reverse_dictionary(input_dict):
                                                                              out = {}
                                                                              for v in input_dict.values():
                                                                              for value in v:
                                                                              if value not in out:
                                                                              out[value.lower()] =

                                                                              for i in input_dict:
                                                                              for j in out:
                                                                              if j in map (lambda x : x.lower(),input_dict[i]):
                                                                              out[j].append(i.lower())
                                                                              out[j].sort()
                                                                              return out


                                                                              this code do like this:



                                                                              r = reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})

                                                                              print(r)

                                                                              {'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}





                                                                              share|improve this answer















                                                                                def reverse_dictionary(input_dict):
                                                                              out = {}
                                                                              for v in input_dict.values():
                                                                              for value in v:
                                                                              if value not in out:
                                                                              out[value.lower()] =

                                                                              for i in input_dict:
                                                                              for j in out:
                                                                              if j in map (lambda x : x.lower(),input_dict[i]):
                                                                              out[j].append(i.lower())
                                                                              out[j].sort()
                                                                              return out


                                                                              this code do like this:



                                                                              r = reverse_dictionary({'Accurate': ['exact', 'precise'], 'exact': ['precise'], 'astute': ['Smart', 'clever'], 'smart': ['clever', 'bright', 'talented']})

                                                                              print(r)

                                                                              {'precise': ['accurate', 'exact'], 'clever': ['astute', 'smart'], 'talented': ['smart'], 'bright': ['smart'], 'exact': ['accurate'], 'smart': ['astute']}






                                                                              share|improve this answer














                                                                              share|improve this answer



                                                                              share|improve this answer








                                                                              edited Jul 14 '18 at 16:06









                                                                              Dr Beco

                                                                              6,94353959




                                                                              6,94353959










                                                                              answered Dec 18 '17 at 16:11









                                                                              Shb8086Shb8086

                                                                              111




                                                                              111













                                                                              • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

                                                                                – Tom Aranda
                                                                                Dec 18 '17 at 16:17











                                                                              • It is a nice solution

                                                                                – Dr Beco
                                                                                Jul 14 '18 at 16:06











                                                                              • It's very nice, but a lot of unexplained decisions (for example, why lower case for keys?)

                                                                                – Liudvikas Akelis
                                                                                Sep 7 '18 at 12:49



















                                                                              • Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

                                                                                – Tom Aranda
                                                                                Dec 18 '17 at 16:17











                                                                              • It is a nice solution

                                                                                – Dr Beco
                                                                                Jul 14 '18 at 16:06











                                                                              • It's very nice, but a lot of unexplained decisions (for example, why lower case for keys?)

                                                                                – Liudvikas Akelis
                                                                                Sep 7 '18 at 12:49

















                                                                              Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

                                                                              – Tom Aranda
                                                                              Dec 18 '17 at 16:17





                                                                              Generally, answers are much more helpful if they include an explanation of what the code is intended to do, and why that solves the problem without introducing others.

                                                                              – Tom Aranda
                                                                              Dec 18 '17 at 16:17













                                                                              It is a nice solution

                                                                              – Dr Beco
                                                                              Jul 14 '18 at 16:06





                                                                              It is a nice solution

                                                                              – Dr Beco
                                                                              Jul 14 '18 at 16:06













                                                                              It's very nice, but a lot of unexplained decisions (for example, why lower case for keys?)

                                                                              – Liudvikas Akelis
                                                                              Sep 7 '18 at 12:49





                                                                              It's very nice, but a lot of unexplained decisions (for example, why lower case for keys?)

                                                                              – Liudvikas Akelis
                                                                              Sep 7 '18 at 12:49











                                                                              0














                                                                              Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))



                                                                              def reverse_dict(dictionary):
                                                                              reverse_dict = {}
                                                                              for key, value in dictionary.iteritems():
                                                                              if not isinstance(value, (list, tuple)):
                                                                              value = [value]
                                                                              for val in value:
                                                                              reverse_dict[val] = reverse_dict.get(val, )
                                                                              reverse_dict[val].append(key)
                                                                              for key, value in reverse_dict.iteritems():
                                                                              if len(value) == 1:
                                                                              reverse_dict[key] = value[0]
                                                                              return reverse_dict





                                                                              share|improve this answer






























                                                                                0














                                                                                Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))



                                                                                def reverse_dict(dictionary):
                                                                                reverse_dict = {}
                                                                                for key, value in dictionary.iteritems():
                                                                                if not isinstance(value, (list, tuple)):
                                                                                value = [value]
                                                                                for val in value:
                                                                                reverse_dict[val] = reverse_dict.get(val, )
                                                                                reverse_dict[val].append(key)
                                                                                for key, value in reverse_dict.iteritems():
                                                                                if len(value) == 1:
                                                                                reverse_dict[key] = value[0]
                                                                                return reverse_dict





                                                                                share|improve this answer




























                                                                                  0












                                                                                  0








                                                                                  0







                                                                                  Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))



                                                                                  def reverse_dict(dictionary):
                                                                                  reverse_dict = {}
                                                                                  for key, value in dictionary.iteritems():
                                                                                  if not isinstance(value, (list, tuple)):
                                                                                  value = [value]
                                                                                  for val in value:
                                                                                  reverse_dict[val] = reverse_dict.get(val, )
                                                                                  reverse_dict[val].append(key)
                                                                                  for key, value in reverse_dict.iteritems():
                                                                                  if len(value) == 1:
                                                                                  reverse_dict[key] = value[0]
                                                                                  return reverse_dict





                                                                                  share|improve this answer















                                                                                  Function is symmetric for values of type list; Tuples are coverted to lists when performing reverse_dict(reverse_dict(dictionary))



                                                                                  def reverse_dict(dictionary):
                                                                                  reverse_dict = {}
                                                                                  for key, value in dictionary.iteritems():
                                                                                  if not isinstance(value, (list, tuple)):
                                                                                  value = [value]
                                                                                  for val in value:
                                                                                  reverse_dict[val] = reverse_dict.get(val, )
                                                                                  reverse_dict[val].append(key)
                                                                                  for key, value in reverse_dict.iteritems():
                                                                                  if len(value) == 1:
                                                                                  reverse_dict[key] = value[0]
                                                                                  return reverse_dict






                                                                                  share|improve this answer














                                                                                  share|improve this answer



                                                                                  share|improve this answer








                                                                                  edited Sep 24 '14 at 12:29

























                                                                                  answered Sep 24 '14 at 12:23









                                                                                  AlfAlf

                                                                                  93




                                                                                  93























                                                                                      0














                                                                                      Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.



                                                                                      def r_maping(dictionary):
                                                                                      List_z=
                                                                                      Map= {}
                                                                                      for z, x in dictionary.iteritems(): #iterate through the keys and values
                                                                                      Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
                                                                                      return Map





                                                                                      share|improve this answer






























                                                                                        0














                                                                                        Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.



                                                                                        def r_maping(dictionary):
                                                                                        List_z=
                                                                                        Map= {}
                                                                                        for z, x in dictionary.iteritems(): #iterate through the keys and values
                                                                                        Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
                                                                                        return Map





                                                                                        share|improve this answer




























                                                                                          0












                                                                                          0








                                                                                          0







                                                                                          Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.



                                                                                          def r_maping(dictionary):
                                                                                          List_z=
                                                                                          Map= {}
                                                                                          for z, x in dictionary.iteritems(): #iterate through the keys and values
                                                                                          Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
                                                                                          return Map





                                                                                          share|improve this answer















                                                                                          Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.



                                                                                          def r_maping(dictionary):
                                                                                          List_z=
                                                                                          Map= {}
                                                                                          for z, x in dictionary.iteritems(): #iterate through the keys and values
                                                                                          Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
                                                                                          return Map






                                                                                          share|improve this answer














                                                                                          share|improve this answer



                                                                                          share|improve this answer








                                                                                          edited Jan 9 '16 at 1:38

























                                                                                          answered Jan 9 '16 at 1:26









                                                                                          EyoelDEyoelD

                                                                                          4651516




                                                                                          4651516























                                                                                              0














                                                                                              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:



                                                                                              def inverse(mapping):
                                                                                              '''
                                                                                              A function to inverse mapping, collecting keys with simillar values
                                                                                              in list. Careful to retain original type and to be fast.
                                                                                              >> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
                                                                                              >> inverse(d)
                                                                                              {1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
                                                                                              '''
                                                                                              res = {}
                                                                                              setdef = res.setdefault
                                                                                              for key, value in mapping.items():
                                                                                              setdef(value, ).append(key)
                                                                                              return res if mapping.__class__==dict else mapping.__class__(res)


                                                                                              Designed to be run under CPython 3.x, for 2.x replace mapping.items() with mapping.iteritems()



                                                                                              On my machine runs a bit faster, than other examples here






                                                                                              share|improve this answer




























                                                                                                0














                                                                                                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:



                                                                                                def inverse(mapping):
                                                                                                '''
                                                                                                A function to inverse mapping, collecting keys with simillar values
                                                                                                in list. Careful to retain original type and to be fast.
                                                                                                >> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
                                                                                                >> inverse(d)
                                                                                                {1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
                                                                                                '''
                                                                                                res = {}
                                                                                                setdef = res.setdefault
                                                                                                for key, value in mapping.items():
                                                                                                setdef(value, ).append(key)
                                                                                                return res if mapping.__class__==dict else mapping.__class__(res)


                                                                                                Designed to be run under CPython 3.x, for 2.x replace mapping.items() with mapping.iteritems()



                                                                                                On my machine runs a bit faster, than other examples here






                                                                                                share|improve this answer


























                                                                                                  0












                                                                                                  0








                                                                                                  0







                                                                                                  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:



                                                                                                  def inverse(mapping):
                                                                                                  '''
                                                                                                  A function to inverse mapping, collecting keys with simillar values
                                                                                                  in list. Careful to retain original type and to be fast.
                                                                                                  >> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
                                                                                                  >> inverse(d)
                                                                                                  {1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
                                                                                                  '''
                                                                                                  res = {}
                                                                                                  setdef = res.setdefault
                                                                                                  for key, value in mapping.items():
                                                                                                  setdef(value, ).append(key)
                                                                                                  return res if mapping.__class__==dict else mapping.__class__(res)


                                                                                                  Designed to be run under CPython 3.x, for 2.x replace mapping.items() with mapping.iteritems()



                                                                                                  On my machine runs a bit faster, than other examples here






                                                                                                  share|improve this answer













                                                                                                  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:



                                                                                                  def inverse(mapping):
                                                                                                  '''
                                                                                                  A function to inverse mapping, collecting keys with simillar values
                                                                                                  in list. Careful to retain original type and to be fast.
                                                                                                  >> d = dict(a=1, b=2, c=1, d=3, e=2, f=1, g=5, h=2)
                                                                                                  >> inverse(d)
                                                                                                  {1: ['f', 'c', 'a'], 2: ['h', 'b', 'e'], 3: ['d'], 5: ['g']}
                                                                                                  '''
                                                                                                  res = {}
                                                                                                  setdef = res.setdefault
                                                                                                  for key, value in mapping.items():
                                                                                                  setdef(value, ).append(key)
                                                                                                  return res if mapping.__class__==dict else mapping.__class__(res)


                                                                                                  Designed to be run under CPython 3.x, for 2.x replace mapping.items() with mapping.iteritems()



                                                                                                  On my machine runs a bit faster, than other examples here







                                                                                                  share|improve this answer












                                                                                                  share|improve this answer



                                                                                                  share|improve this answer










                                                                                                  answered Aug 2 '16 at 18:08









                                                                                                  thodnevthodnev

                                                                                                  970616




                                                                                                  970616























                                                                                                      0














                                                                                                      If values aren't unique AND may be a hash (one dimension):



                                                                                                      for k, v in myDict.items():
                                                                                                      if len(v) > 1:
                                                                                                      for item in v:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)


                                                                                                      And with a recursion if you need to dig deeper then just one dimension:



                                                                                                      def digList(lst):
                                                                                                      temp =
                                                                                                      for item in lst:
                                                                                                      if type(item) is list:
                                                                                                      temp.append(digList(item))
                                                                                                      else:
                                                                                                      temp.append(item)
                                                                                                      return set(temp)

                                                                                                      for k, v in myDict.items():
                                                                                                      if type(v) is list:
                                                                                                      items = digList(v)
                                                                                                      for item in items:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)





                                                                                                      share|improve this answer


























                                                                                                      • You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, ) lines

                                                                                                        – gabuzo
                                                                                                        Oct 24 '17 at 8:22
















                                                                                                      0














                                                                                                      If values aren't unique AND may be a hash (one dimension):



                                                                                                      for k, v in myDict.items():
                                                                                                      if len(v) > 1:
                                                                                                      for item in v:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)


                                                                                                      And with a recursion if you need to dig deeper then just one dimension:



                                                                                                      def digList(lst):
                                                                                                      temp =
                                                                                                      for item in lst:
                                                                                                      if type(item) is list:
                                                                                                      temp.append(digList(item))
                                                                                                      else:
                                                                                                      temp.append(item)
                                                                                                      return set(temp)

                                                                                                      for k, v in myDict.items():
                                                                                                      if type(v) is list:
                                                                                                      items = digList(v)
                                                                                                      for item in items:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)





                                                                                                      share|improve this answer


























                                                                                                      • You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, ) lines

                                                                                                        – gabuzo
                                                                                                        Oct 24 '17 at 8:22














                                                                                                      0












                                                                                                      0








                                                                                                      0







                                                                                                      If values aren't unique AND may be a hash (one dimension):



                                                                                                      for k, v in myDict.items():
                                                                                                      if len(v) > 1:
                                                                                                      for item in v:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)


                                                                                                      And with a recursion if you need to dig deeper then just one dimension:



                                                                                                      def digList(lst):
                                                                                                      temp =
                                                                                                      for item in lst:
                                                                                                      if type(item) is list:
                                                                                                      temp.append(digList(item))
                                                                                                      else:
                                                                                                      temp.append(item)
                                                                                                      return set(temp)

                                                                                                      for k, v in myDict.items():
                                                                                                      if type(v) is list:
                                                                                                      items = digList(v)
                                                                                                      for item in items:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)





                                                                                                      share|improve this answer















                                                                                                      If values aren't unique AND may be a hash (one dimension):



                                                                                                      for k, v in myDict.items():
                                                                                                      if len(v) > 1:
                                                                                                      for item in v:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)


                                                                                                      And with a recursion if you need to dig deeper then just one dimension:



                                                                                                      def digList(lst):
                                                                                                      temp =
                                                                                                      for item in lst:
                                                                                                      if type(item) is list:
                                                                                                      temp.append(digList(item))
                                                                                                      else:
                                                                                                      temp.append(item)
                                                                                                      return set(temp)

                                                                                                      for k, v in myDict.items():
                                                                                                      if type(v) is list:
                                                                                                      items = digList(v)
                                                                                                      for item in items:
                                                                                                      invDict[item] = invDict.get(item, )
                                                                                                      invDict[item].append(k)
                                                                                                      else:
                                                                                                      invDict[v] = invDict.get(v, )
                                                                                                      invDict[v].append(k)






                                                                                                      share|improve this answer














                                                                                                      share|improve this answer



                                                                                                      share|improve this answer








                                                                                                      edited Jan 10 '17 at 11:06

























                                                                                                      answered Jan 10 '17 at 10:37









                                                                                                      mveithmveith

                                                                                                      13




                                                                                                      13













                                                                                                      • You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, ) lines

                                                                                                        – gabuzo
                                                                                                        Oct 24 '17 at 8:22



















                                                                                                      • You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, ) lines

                                                                                                        – gabuzo
                                                                                                        Oct 24 '17 at 8:22

















                                                                                                      You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, ) lines

                                                                                                      – gabuzo
                                                                                                      Oct 24 '17 at 8:22





                                                                                                      You might improve your solutions using a defaultdict: it'll remove all the invDict[item] = invDict.get(item, ) lines

                                                                                                      – gabuzo
                                                                                                      Oct 24 '17 at 8:22











                                                                                                      0














                                                                                                      Inverse your dictionary:



                                                                                                      dict_ = {"k0":"v0", "k1":"v1", "k2":"v1"}
                                                                                                      inversed_dict_ = {val: key for key, val in dict_.items()}

                                                                                                      print(inversed_dict_["v1"])





                                                                                                      share|improve this answer




























                                                                                                        0














                                                                                                        Inverse your dictionary:



                                                                                                        dict_ = {"k0":"v0", "k1":"v1", "k2":"v1"}
                                                                                                        inversed_dict_ = {val: key for key, val in dict_.items()}

                                                                                                        print(inversed_dict_["v1"])





                                                                                                        share|improve this answer


























                                                                                                          0












                                                                                                          0








                                                                                                          0







                                                                                                          Inverse your dictionary:



                                                                                                          dict_ = {"k0":"v0", "k1":"v1", "k2":"v1"}
                                                                                                          inversed_dict_ = {val: key for key, val in dict_.items()}

                                                                                                          print(inversed_dict_["v1"])





                                                                                                          share|improve this answer













                                                                                                          Inverse your dictionary:



                                                                                                          dict_ = {"k0":"v0", "k1":"v1", "k2":"v1"}
                                                                                                          inversed_dict_ = {val: key for key, val in dict_.items()}

                                                                                                          print(inversed_dict_["v1"])






                                                                                                          share|improve this answer












                                                                                                          share|improve this answer



                                                                                                          share|improve this answer










                                                                                                          answered Jun 7 '18 at 23:37









                                                                                                          MiladioussMiladiouss

                                                                                                          553614




                                                                                                          553614























                                                                                                              0














                                                                                                              As per my comment to the question. I think the easiest and one liner which works for both Python2 and Python 3 will be



                                                                                                              dict(zip(inv_map.values(), inv_map.keys()))





                                                                                                              share|improve this answer




























                                                                                                                0














                                                                                                                As per my comment to the question. I think the easiest and one liner which works for both Python2 and Python 3 will be



                                                                                                                dict(zip(inv_map.values(), inv_map.keys()))





                                                                                                                share|improve this answer


























                                                                                                                  0












                                                                                                                  0








                                                                                                                  0







                                                                                                                  As per my comment to the question. I think the easiest and one liner which works for both Python2 and Python 3 will be



                                                                                                                  dict(zip(inv_map.values(), inv_map.keys()))





                                                                                                                  share|improve this answer













                                                                                                                  As per my comment to the question. I think the easiest and one liner which works for both Python2 and Python 3 will be



                                                                                                                  dict(zip(inv_map.values(), inv_map.keys()))






                                                                                                                  share|improve this answer












                                                                                                                  share|improve this answer



                                                                                                                  share|improve this answer










                                                                                                                  answered Nov 7 '18 at 22:36









                                                                                                                  Seshadri VSSeshadri VS

                                                                                                                  308114




                                                                                                                  308114























                                                                                                                      0














                                                                                                                      For instance, you have the following dictionary:



                                                                                                                      dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}


                                                                                                                      And you wanna get it in such an inverted form:



                                                                                                                      inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}


                                                                                                                      First Solution. For inverting key-value pairs in your dictionary use a for-loop approach:



                                                                                                                      # Use this code to invert dictionaries that have non-unique values

                                                                                                                      inverted_dict = dictio()
                                                                                                                      for key, value in dict.items():
                                                                                                                      inverted_dict.setdefault(value, list()).append(key)


                                                                                                                      Second Solution. Use a dictionary comprehension approach for inversion:



                                                                                                                      # Use this code to invert dictionaries that have unique values

                                                                                                                      inverted_dict = {value: key for key, value in dict.items()}


                                                                                                                      Third Solution. Use reverting the inversion approach:



                                                                                                                      # Use this code to invert dictionaries that have lists of values

                                                                                                                      dict = {value: key for key in inverted_dict for value in my_map[key]}





                                                                                                                      share|improve this answer






























                                                                                                                        0














                                                                                                                        For instance, you have the following dictionary:



                                                                                                                        dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}


                                                                                                                        And you wanna get it in such an inverted form:



                                                                                                                        inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}


                                                                                                                        First Solution. For inverting key-value pairs in your dictionary use a for-loop approach:



                                                                                                                        # Use this code to invert dictionaries that have non-unique values

                                                                                                                        inverted_dict = dictio()
                                                                                                                        for key, value in dict.items():
                                                                                                                        inverted_dict.setdefault(value, list()).append(key)


                                                                                                                        Second Solution. Use a dictionary comprehension approach for inversion:



                                                                                                                        # Use this code to invert dictionaries that have unique values

                                                                                                                        inverted_dict = {value: key for key, value in dict.items()}


                                                                                                                        Third Solution. Use reverting the inversion approach:



                                                                                                                        # Use this code to invert dictionaries that have lists of values

                                                                                                                        dict = {value: key for key in inverted_dict for value in my_map[key]}





                                                                                                                        share|improve this answer




























                                                                                                                          0












                                                                                                                          0








                                                                                                                          0







                                                                                                                          For instance, you have the following dictionary:



                                                                                                                          dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}


                                                                                                                          And you wanna get it in such an inverted form:



                                                                                                                          inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}


                                                                                                                          First Solution. For inverting key-value pairs in your dictionary use a for-loop approach:



                                                                                                                          # Use this code to invert dictionaries that have non-unique values

                                                                                                                          inverted_dict = dictio()
                                                                                                                          for key, value in dict.items():
                                                                                                                          inverted_dict.setdefault(value, list()).append(key)


                                                                                                                          Second Solution. Use a dictionary comprehension approach for inversion:



                                                                                                                          # Use this code to invert dictionaries that have unique values

                                                                                                                          inverted_dict = {value: key for key, value in dict.items()}


                                                                                                                          Third Solution. Use reverting the inversion approach:



                                                                                                                          # Use this code to invert dictionaries that have lists of values

                                                                                                                          dict = {value: key for key in inverted_dict for value in my_map[key]}





                                                                                                                          share|improve this answer















                                                                                                                          For instance, you have the following dictionary:



                                                                                                                          dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}


                                                                                                                          And you wanna get it in such an inverted form:



                                                                                                                          inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}


                                                                                                                          First Solution. For inverting key-value pairs in your dictionary use a for-loop approach:



                                                                                                                          # Use this code to invert dictionaries that have non-unique values

                                                                                                                          inverted_dict = dictio()
                                                                                                                          for key, value in dict.items():
                                                                                                                          inverted_dict.setdefault(value, list()).append(key)


                                                                                                                          Second Solution. Use a dictionary comprehension approach for inversion:



                                                                                                                          # Use this code to invert dictionaries that have unique values

                                                                                                                          inverted_dict = {value: key for key, value in dict.items()}


                                                                                                                          Third Solution. Use reverting the inversion approach:



                                                                                                                          # Use this code to invert dictionaries that have lists of values

                                                                                                                          dict = {value: key for key in inverted_dict for value in my_map[key]}






                                                                                                                          share|improve this answer














                                                                                                                          share|improve this answer



                                                                                                                          share|improve this answer








                                                                                                                          edited Jan 20 at 14:13









                                                                                                                          Martijn Pieters

                                                                                                                          711k13724812301




                                                                                                                          711k13724812301










                                                                                                                          answered Jan 10 at 5:55









                                                                                                                          ARGeoARGeo

                                                                                                                          5,27952649




                                                                                                                          5,27952649























                                                                                                                              -1














                                                                                                                              Fast functional solution for non-bijective maps (values not unique):



                                                                                                                              from itertools import imap, groupby

                                                                                                                              def fst(s):
                                                                                                                              return s[0]

                                                                                                                              def snd(s):
                                                                                                                              return s[1]

                                                                                                                              def inverseDict(d):
                                                                                                                              """
                                                                                                                              input d: a -> b
                                                                                                                              output : b -> set(a)
                                                                                                                              """
                                                                                                                              return {
                                                                                                                              v : set(imap(fst, kv_iter))
                                                                                                                              for (v, kv_iter) in groupby(
                                                                                                                              sorted(d.iteritems(),
                                                                                                                              key=snd),
                                                                                                                              key=snd
                                                                                                                              )
                                                                                                                              }


                                                                                                                              In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.



                                                                                                                              Unfortunately the values have to be sortable, the sorting is required by groupby.






                                                                                                                              share|improve this answer


























                                                                                                                              • "In theory this should be faster than adding to the set (or appending to the list) one by one" - no. Given n elements in the original dict, your approach has O(n log n) time complexity due to the need to sort the dict's items, whereas the naive imperative approach has O(n) time complexity. For all I know your approach may be faster up until absurdly large dicts in practice, but it certainly isn't faster in theory.

                                                                                                                                – Mark Amery
                                                                                                                                Jul 16 '16 at 18:17


















                                                                                                                              -1














                                                                                                                              Fast functional solution for non-bijective maps (values not unique):



                                                                                                                              from itertools import imap, groupby

                                                                                                                              def fst(s):
                                                                                                                              return s[0]

                                                                                                                              def snd(s):
                                                                                                                              return s[1]

                                                                                                                              def inverseDict(d):
                                                                                                                              """
                                                                                                                              input d: a -> b
                                                                                                                              output : b -> set(a)
                                                                                                                              """
                                                                                                                              return {
                                                                                                                              v : set(imap(fst, kv_iter))
                                                                                                                              for (v, kv_iter) in groupby(
                                                                                                                              sorted(d.iteritems(),
                                                                                                                              key=snd),
                                                                                                                              key=snd
                                                                                                                              )
                                                                                                                              }


                                                                                                                              In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.



                                                                                                                              Unfortunately the values have to be sortable, the sorting is required by groupby.






                                                                                                                              share|improve this answer


























                                                                                                                              • "In theory this should be faster than adding to the set (or appending to the list) one by one" - no. Given n elements in the original dict, your approach has O(n log n) time complexity due to the need to sort the dict's items, whereas the naive imperative approach has O(n) time complexity. For all I know your approach may be faster up until absurdly large dicts in practice, but it certainly isn't faster in theory.

                                                                                                                                – Mark Amery
                                                                                                                                Jul 16 '16 at 18:17
















                                                                                                                              -1












                                                                                                                              -1








                                                                                                                              -1







                                                                                                                              Fast functional solution for non-bijective maps (values not unique):



                                                                                                                              from itertools import imap, groupby

                                                                                                                              def fst(s):
                                                                                                                              return s[0]

                                                                                                                              def snd(s):
                                                                                                                              return s[1]

                                                                                                                              def inverseDict(d):
                                                                                                                              """
                                                                                                                              input d: a -> b
                                                                                                                              output : b -> set(a)
                                                                                                                              """
                                                                                                                              return {
                                                                                                                              v : set(imap(fst, kv_iter))
                                                                                                                              for (v, kv_iter) in groupby(
                                                                                                                              sorted(d.iteritems(),
                                                                                                                              key=snd),
                                                                                                                              key=snd
                                                                                                                              )
                                                                                                                              }


                                                                                                                              In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.



                                                                                                                              Unfortunately the values have to be sortable, the sorting is required by groupby.






                                                                                                                              share|improve this answer















                                                                                                                              Fast functional solution for non-bijective maps (values not unique):



                                                                                                                              from itertools import imap, groupby

                                                                                                                              def fst(s):
                                                                                                                              return s[0]

                                                                                                                              def snd(s):
                                                                                                                              return s[1]

                                                                                                                              def inverseDict(d):
                                                                                                                              """
                                                                                                                              input d: a -> b
                                                                                                                              output : b -> set(a)
                                                                                                                              """
                                                                                                                              return {
                                                                                                                              v : set(imap(fst, kv_iter))
                                                                                                                              for (v, kv_iter) in groupby(
                                                                                                                              sorted(d.iteritems(),
                                                                                                                              key=snd),
                                                                                                                              key=snd
                                                                                                                              )
                                                                                                                              }


                                                                                                                              In theory this should be faster than adding to the set (or appending to the list) one by one like in the imperative solution.



                                                                                                                              Unfortunately the values have to be sortable, the sorting is required by groupby.







                                                                                                                              share|improve this answer














                                                                                                                              share|improve this answer



                                                                                                                              share|improve this answer








                                                                                                                              edited May 23 '17 at 12:10









                                                                                                                              Community

                                                                                                                              11




                                                                                                                              11










                                                                                                                              answered Mar 6 '14 at 20:50









                                                                                                                              cjaycjay

                                                                                                                              152




                                                                                                                              152













                                                                                                                              • "In theory this should be faster than adding to the set (or appending to the list) one by one" - no. Given n elements in the original dict, your approach has O(n log n) time complexity due to the need to sort the dict's items, whereas the naive imperative approach has O(n) time complexity. For all I know your approach may be faster up until absurdly large dicts in practice, but it certainly isn't faster in theory.

                                                                                                                                – Mark Amery
                                                                                                                                Jul 16 '16 at 18:17





















                                                                                                                              • "In theory this should be faster than adding to the set (or appending to the list) one by one" - no. Given n elements in the original dict, your approach has O(n log n) time complexity due to the need to sort the dict's items, whereas the naive imperative approach has O(n) time complexity. For all I know your approach may be faster up until absurdly large dicts in practice, but it certainly isn't faster in theory.

                                                                                                                                – Mark Amery
                                                                                                                                Jul 16 '16 at 18:17



















                                                                                                                              "In theory this should be faster than adding to the set (or appending to the list) one by one" - no. Given n elements in the original dict, your approach has O(n log n) time complexity due to the need to sort the dict's items, whereas the naive imperative approach has O(n) time complexity. For all I know your approach may be faster up until absurdly large dicts in practice, but it certainly isn't faster in theory.

                                                                                                                              – Mark Amery
                                                                                                                              Jul 16 '16 at 18:17







                                                                                                                              "In theory this should be faster than adding to the set (or appending to the list) one by one" - no. Given n elements in the original dict, your approach has O(n log n) time complexity due to the need to sort the dict's items, whereas the naive imperative approach has O(n) time complexity. For all I know your approach may be faster up until absurdly large dicts in practice, but it certainly isn't faster in theory.

                                                                                                                              – Mark Amery
                                                                                                                              Jul 16 '16 at 18:17













                                                                                                                              -1














                                                                                                                              I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.



                                                                                                                              def dict_invert(map1):
                                                                                                                              inv_map = {} # new dictionary
                                                                                                                              for key in map1.keys():
                                                                                                                              inv_map[map1.get(key)] = key
                                                                                                                              return inv_map





                                                                                                                              share|improve this answer






























                                                                                                                                -1














                                                                                                                                I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.



                                                                                                                                def dict_invert(map1):
                                                                                                                                inv_map = {} # new dictionary
                                                                                                                                for key in map1.keys():
                                                                                                                                inv_map[map1.get(key)] = key
                                                                                                                                return inv_map





                                                                                                                                share|improve this answer




























                                                                                                                                  -1












                                                                                                                                  -1








                                                                                                                                  -1







                                                                                                                                  I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.



                                                                                                                                  def dict_invert(map1):
                                                                                                                                  inv_map = {} # new dictionary
                                                                                                                                  for key in map1.keys():
                                                                                                                                  inv_map[map1.get(key)] = key
                                                                                                                                  return inv_map





                                                                                                                                  share|improve this answer















                                                                                                                                  I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.



                                                                                                                                  def dict_invert(map1):
                                                                                                                                  inv_map = {} # new dictionary
                                                                                                                                  for key in map1.keys():
                                                                                                                                  inv_map[map1.get(key)] = key
                                                                                                                                  return inv_map






                                                                                                                                  share|improve this answer














                                                                                                                                  share|improve this answer



                                                                                                                                  share|improve this answer








                                                                                                                                  edited Aug 5 '16 at 21:14

























                                                                                                                                  answered Aug 5 '16 at 19:47









                                                                                                                                  Taras VoitovychTaras Voitovych

                                                                                                                                  92




                                                                                                                                  92























                                                                                                                                      -3














                                                                                                                                      For all kinds of dictionary, no matter if they don't have unique values to use as keys, you can create a list of keys for each value



                                                                                                                                      inv_map = {v: inv_map.get(v, ) + [k] for k,v in my_map.items()}





                                                                                                                                      share|improve this answer


























                                                                                                                                      • have you tested it for non-unique values? e.g. map = { 'a': 1, 'b':2, 'c':1 } gives {1: ['c'], 2: ['b']} for inv_map, 'a' gets lost (I put inv_map = {} before your line)

                                                                                                                                        – Matthias 009
                                                                                                                                        May 1 '12 at 16:36






                                                                                                                                      • 1





                                                                                                                                        This doesn't work, because the new value of inv_map is not assigned until the comprehension completes

                                                                                                                                        – Eric
                                                                                                                                        Jul 30 '14 at 15:11
















                                                                                                                                      -3














                                                                                                                                      For all kinds of dictionary, no matter if they don't have unique values to use as keys, you can create a list of keys for each value



                                                                                                                                      inv_map = {v: inv_map.get(v, ) + [k] for k,v in my_map.items()}





                                                                                                                                      share|improve this answer


























                                                                                                                                      • have you tested it for non-unique values? e.g. map = { 'a': 1, 'b':2, 'c':1 } gives {1: ['c'], 2: ['b']} for inv_map, 'a' gets lost (I put inv_map = {} before your line)

                                                                                                                                        – Matthias 009
                                                                                                                                        May 1 '12 at 16:36






                                                                                                                                      • 1





                                                                                                                                        This doesn't work, because the new value of inv_map is not assigned until the comprehension completes

                                                                                                                                        – Eric
                                                                                                                                        Jul 30 '14 at 15:11














                                                                                                                                      -3












                                                                                                                                      -3








                                                                                                                                      -3







                                                                                                                                      For all kinds of dictionary, no matter if they don't have unique values to use as keys, you can create a list of keys for each value



                                                                                                                                      inv_map = {v: inv_map.get(v, ) + [k] for k,v in my_map.items()}





                                                                                                                                      share|improve this answer















                                                                                                                                      For all kinds of dictionary, no matter if they don't have unique values to use as keys, you can create a list of keys for each value



                                                                                                                                      inv_map = {v: inv_map.get(v, ) + [k] for k,v in my_map.items()}






                                                                                                                                      share|improve this answer














                                                                                                                                      share|improve this answer



                                                                                                                                      share|improve this answer








                                                                                                                                      edited Aug 21 '16 at 12:53









                                                                                                                                      Rick Teachey

                                                                                                                                      15.6k73965




                                                                                                                                      15.6k73965










                                                                                                                                      answered Nov 1 '10 at 17:55









                                                                                                                                      becobeco

                                                                                                                                      111




                                                                                                                                      111













                                                                                                                                      • have you tested it for non-unique values? e.g. map = { 'a': 1, 'b':2, 'c':1 } gives {1: ['c'], 2: ['b']} for inv_map, 'a' gets lost (I put inv_map = {} before your line)

                                                                                                                                        – Matthias 009
                                                                                                                                        May 1 '12 at 16:36






                                                                                                                                      • 1





                                                                                                                                        This doesn't work, because the new value of inv_map is not assigned until the comprehension completes

                                                                                                                                        – Eric
                                                                                                                                        Jul 30 '14 at 15:11



















                                                                                                                                      • have you tested it for non-unique values? e.g. map = { 'a': 1, 'b':2, 'c':1 } gives {1: ['c'], 2: ['b']} for inv_map, 'a' gets lost (I put inv_map = {} before your line)

                                                                                                                                        – Matthias 009
                                                                                                                                        May 1 '12 at 16:36






                                                                                                                                      • 1





                                                                                                                                        This doesn't work, because the new value of inv_map is not assigned until the comprehension completes

                                                                                                                                        – Eric
                                                                                                                                        Jul 30 '14 at 15:11

















                                                                                                                                      have you tested it for non-unique values? e.g. map = { 'a': 1, 'b':2, 'c':1 } gives {1: ['c'], 2: ['b']} for inv_map, 'a' gets lost (I put inv_map = {} before your line)

                                                                                                                                      – Matthias 009
                                                                                                                                      May 1 '12 at 16:36





                                                                                                                                      have you tested it for non-unique values? e.g. map = { 'a': 1, 'b':2, 'c':1 } gives {1: ['c'], 2: ['b']} for inv_map, 'a' gets lost (I put inv_map = {} before your line)

                                                                                                                                      – Matthias 009
                                                                                                                                      May 1 '12 at 16:36




                                                                                                                                      1




                                                                                                                                      1





                                                                                                                                      This doesn't work, because the new value of inv_map is not assigned until the comprehension completes

                                                                                                                                      – Eric
                                                                                                                                      Jul 30 '14 at 15:11





                                                                                                                                      This doesn't work, because the new value of inv_map is not assigned until the comprehension completes

                                                                                                                                      – Eric
                                                                                                                                      Jul 30 '14 at 15:11











                                                                                                                                      -3














                                                                                                                                      This is not the best solution, but it works. Let's say the dictionary we want to reverse is:



                                                                                                                                      dictionary = {'a': 1, 'b': 2, 'c': 3}, then:



                                                                                                                                      dictionary = {'a': 1, 'b': 2, 'c': 3}
                                                                                                                                      reverse_dictionary = {}
                                                                                                                                      for index, val in enumerate(list(dictionary.values())):
                                                                                                                                      reverse_dictionary[val] = list(dictionary.keys())[index]


                                                                                                                                      The output of reverse_dictionary, should be {1: 'a', 2: 'b', 3: 'c'}






                                                                                                                                      share|improve this answer






























                                                                                                                                        -3














                                                                                                                                        This is not the best solution, but it works. Let's say the dictionary we want to reverse is:



                                                                                                                                        dictionary = {'a': 1, 'b': 2, 'c': 3}, then:



                                                                                                                                        dictionary = {'a': 1, 'b': 2, 'c': 3}
                                                                                                                                        reverse_dictionary = {}
                                                                                                                                        for index, val in enumerate(list(dictionary.values())):
                                                                                                                                        reverse_dictionary[val] = list(dictionary.keys())[index]


                                                                                                                                        The output of reverse_dictionary, should be {1: 'a', 2: 'b', 3: 'c'}






                                                                                                                                        share|improve this answer




























                                                                                                                                          -3












                                                                                                                                          -3








                                                                                                                                          -3







                                                                                                                                          This is not the best solution, but it works. Let's say the dictionary we want to reverse is:



                                                                                                                                          dictionary = {'a': 1, 'b': 2, 'c': 3}, then:



                                                                                                                                          dictionary = {'a': 1, 'b': 2, 'c': 3}
                                                                                                                                          reverse_dictionary = {}
                                                                                                                                          for index, val in enumerate(list(dictionary.values())):
                                                                                                                                          reverse_dictionary[val] = list(dictionary.keys())[index]


                                                                                                                                          The output of reverse_dictionary, should be {1: 'a', 2: 'b', 3: 'c'}






                                                                                                                                          share|improve this answer















                                                                                                                                          This is not the best solution, but it works. Let's say the dictionary we want to reverse is:



                                                                                                                                          dictionary = {'a': 1, 'b': 2, 'c': 3}, then:



                                                                                                                                          dictionary = {'a': 1, 'b': 2, 'c': 3}
                                                                                                                                          reverse_dictionary = {}
                                                                                                                                          for index, val in enumerate(list(dictionary.values())):
                                                                                                                                          reverse_dictionary[val] = list(dictionary.keys())[index]


                                                                                                                                          The output of reverse_dictionary, should be {1: 'a', 2: 'b', 3: 'c'}







                                                                                                                                          share|improve this answer














                                                                                                                                          share|improve this answer



                                                                                                                                          share|improve this answer








                                                                                                                                          edited Jun 16 '18 at 12:23

























                                                                                                                                          answered Jun 9 '18 at 12:20









                                                                                                                                          user9918114user9918114

                                                                                                                                          11




                                                                                                                                          11






















                                                                                                                                              1 2
                                                                                                                                              next

















                                                                                                                                              draft saved

                                                                                                                                              draft discarded




















































                                                                                                                                              Thanks for contributing an answer to Stack Overflow!


                                                                                                                                              • Please be sure to answer the question. Provide details and share your research!

                                                                                                                                              But avoid



                                                                                                                                              • Asking for help, clarification, or responding to other answers.

                                                                                                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                                                                                                              To learn more, see our tips on writing great answers.




                                                                                                                                              draft saved


                                                                                                                                              draft discarded














                                                                                                                                              StackExchange.ready(
                                                                                                                                              function () {
                                                                                                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f483666%2fpython-reverse-invert-a-mapping%23new-answer', 'question_page');
                                                                                                                                              }
                                                                                                                                              );

                                                                                                                                              Post as a guest















                                                                                                                                              Required, but never shown





















































                                                                                                                                              Required, but never shown














                                                                                                                                              Required, but never shown












                                                                                                                                              Required, but never shown







                                                                                                                                              Required, but never shown

































                                                                                                                                              Required, but never shown














                                                                                                                                              Required, but never shown












                                                                                                                                              Required, but never shown







                                                                                                                                              Required, but never shown











                                                                                                                                              Popular posts from this blog

                                                                                                                                              Homophylophilia

                                                                                                                                              Updating UILabel text programmatically using a function

                                                                                                                                              Cloud Functions - OpenCV Videocapture Read method fails for larger files from cloud storage