A data-structure for 1:1 mappings in python?

前端 未结 8 1504
广开言路
广开言路 2020-12-17 08:17

I have a problem which requires a reversable 1:1 mapping of keys to values.

That means sometimes I want to find the value given a key, but at other times I want to

8条回答
  •  既然无缘
    2020-12-17 08:25

    It so happens that I find myself asking this question all the time (yesterday in particular). I agree with the approach of making two dictionaries. Do some benchmarking to see how much memory it's taking. I've never needed to make it mutable, but here's how I abstract it, if it's of any use:

    class BiDict(list):
        def __init__(self,*pairs):
            super(list,self).__init__(pairs)
            self._first_access = {}
            self._second_access = {}
            for pair in pairs:
                self._first_access[pair[0]] = pair[1]
                self._second_access[pair[1]] = pair[0]
                self.append(pair)
    
        def _get_by_first(self,key):
            return self._first_access[key]
    
        def _get_by_second(self,key):
            return self._second_access[key]
    
        # You'll have to do some overrides to make it mutable
        # Methods such as append, __add__, __del__, __iadd__
        # to name a few will have to maintain ._*_access
    
    class Constants(BiDict):
        # An implementation expecting an integer and a string
        get_by_name = BiDict._get_by_second
        get_by_number = BiDict._get_by_first
    
    t = Constants(
            ( 1, 'foo'),
            ( 5, 'bar'),
            ( 8, 'baz'),
        )
    
    >>> print t.get_by_number(5)
    bar
    >>> print t.get_by_name('baz')
    8
    >>> print t
    [(1, 'foo'), (5, 'bar'), (8, 'baz')]
    

提交回复
热议问题