Reverse / invert a dictionary mapping

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

    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']}

提交回复
热议问题