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

前端 未结 8 1526
广开言路
广开言路 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:41

    Here is my own solution to this problem: http://github.com/spenthil/pymathmap/blob/master/pymathmap.py

    The goal is to make it as transparent to the user as possible. The only introduced significant attribute is partner.

    OneToOneDict subclasses from dict - I know that isn't generally recommended, but I think I have the common use cases covered. The backend is pretty simple, it (dict1) keeps a weakref to a 'partner' OneToOneDict (dict2) which is its inverse. When dict1 is modified dict2 is updated accordingly as well and vice versa.

    From the docstring:

    >>> dict1 = OneToOneDict()
    >>> dict2 = OneToOneDict()
    >>> dict1.partner = dict2
    >>> assert(dict1 is dict2.partner)
    >>> assert(dict2 is dict1.partner)
    >>> dict1['one'] = '1'
    >>> dict2['2'] = '1'
    >>> dict1['one'] = 'wow'
    >>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
    >>> dict1['one'] = '1'
    >>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
    >>> dict1.update({'three': '3', 'four': '4'})
    >>> assert(dict1 == dict((v,k) for k,v in dict2.items()))
    >>> dict3 = OneToOneDict({'4':'four'})
    >>> assert(dict3.partner is None)
    >>> assert(dict3 == {'4':'four'})
    >>> dict1.partner = dict3
    >>> assert(dict1.partner is not dict2)
    >>> assert(dict2.partner is None)
    >>> assert(dict1.partner is dict3)
    >>> assert(dict3.partner is dict1)
    >>> dict1.setdefault('five', '5')
    >>> dict1['five']
    '5'
    >>> dict1.setdefault('five', '0')
    >>> dict1['five']
    '5'
    

    When I get some free time, I intend to make a version that doesn't store things twice. No clue when that'll be though :)

提交回复
热议问题