Reverse / invert a dictionary mapping

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

    For instance, you have the following dictionary:

    dict = {'a': 'fire', 'b': 'ice', 'c': 'fire', 'd': 'water'}
    

    And you wanna get it in such an inverted form:

    inverted_dict = {'fire': ['a', 'c'], 'ice': ['b'], 'water': ['d']}
    

    First Solution. For inverting key-value pairs in your dictionary use a for-loop approach:

    # Use this code to invert dictionaries that have non-unique values
    
    inverted_dict = dict()
    for key, value in dict.items():
        inverted_dict.setdefault(value, list()).append(key)
    

    Second Solution. Use a dictionary comprehension approach for inversion:

    # Use this code to invert dictionaries that have unique values
    
    inverted_dict = {value: key for key, value in dict.items()}
    

    Third Solution. Use reverting the inversion approach (relies on second solution):

    # Use this code to invert dictionaries that have lists of values
    
    dict = {value: key for key in inverted_dict for value in my_map[key]}
    

提交回复
热议问题