Reverse / invert a dictionary mapping

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

    I think the best way to do this is to define a class. Here is an implementation of a "symmetric dictionary":

    class SymDict:
        def __init__(self):
            self.aToB = {}
            self.bToA = {}
    
        def assocAB(self, a, b):
            # Stores and returns a tuple (a,b) of overwritten bindings
            currB = None
            if a in self.aToB: currB = self.bToA[a]
            currA = None
            if b in self.bToA: currA = self.aToB[b]
    
            self.aToB[a] = b
            self.bToA[b] = a
            return (currA, currB)
    
        def lookupA(self, a):
            if a in self.aToB:
                return self.aToB[a]
            return None
    
        def lookupB(self, b):
            if b in self.bToA:
                return self.bToA[b]
            return None
    

    Deletion and iteration methods are easy enough to implement if they're needed.

    This implementation is way more efficient than inverting an entire dictionary (which seems to be the most popular solution on this page). Not to mention, you can add or remove values from your SymDict as much as you want, and your inverse-dictionary will always stay valid -- this isn't true if you simply reverse the entire dictionary once.

提交回复
热议问题