Reverse / invert a dictionary mapping

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

    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
    

提交回复
热议问题