Reverse / invert a dictionary mapping

前端 未结 26 2271
一整个雨季
一整个雨季 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 12:06

    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.

提交回复
热议问题