Reverse / invert a dictionary mapping

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

    To do this while preserving the type of your mapping (assuming that it is a dict or a dict subclass):

    def inverse_mapping(f):
        return f.__class__(map(reversed, f.items()))
    

提交回复
热议问题