Reverse / invert a dictionary mapping

前端 未结 26 2311
一整个雨季
一整个雨季 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 12:03

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

提交回复
热议问题