Reverse / invert a dictionary mapping

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

    Since dictionaries require one unique key within the dictionary unlike values, we have to append the reversed values into a list of sort to be included within the new specific keys.

    def r_maping(dictionary):
        List_z=[]
        Map= {}
        for z, x in dictionary.iteritems(): #iterate through the keys and values
            Map.setdefault(x,List_z).append(z) #Setdefault is the same as dict[key]=default."The method returns the key value available in the dictionary and if given key is not available then it will return provided default value. Afterward, we will append into the default list our new values for the specific key.
        return Map
    
    0 讨论(0)
  • 2020-11-21 12:15

    I wrote this with the help of cycle 'for' and method '.get()' and I changed the name 'map' of the dictionary to 'map1' because 'map' is a function.

    def dict_invert(map1):
        inv_map = {} # new dictionary
        for key in map1.keys():
            inv_map[map1.get(key)] = key
        return inv_map
    
    0 讨论(0)
提交回复
热议问题