Reverse / invert a dictionary mapping

前端 未结 26 2239
一整个雨季
一整个雨季 2020-11-21 11:47

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\'         


        
26条回答
  •  独厮守ぢ
    2020-11-21 11:56

    This expands upon the answer by Robert, 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 could exist unordered applications for which this makes sense, instead of setdefault(v, []).append(k), use setdefault(v, set()).add(k).

提交回复
热议问题