Is there a 'multimap' implementation in Python?

后端 未结 8 1627
离开以前
离开以前 2020-12-01 01:26

I am new to Python, and I am familiar with implementations of Multimaps in other languages. Does Python have such a data structure built-in, or available in a commonly-used

相关标签:
8条回答
  • 2020-12-01 01:56

    Or subclass dict:

    class Multimap(dict):
        def __setitem__(self, key, value):
            if key not in self:
                dict.__setitem__(self, key, [value])  # call super method to avoid recursion
            else
                self[key].append(value)
    
    0 讨论(0)
  • 2020-12-01 01:57

    I do not clearly understand the semantics of your example

    a[1] = 'a'
    a[1] = 'b' #??
    

    Is second line a[1] = 'b' supposed to replace the element at [1]. If yes, then you need to use dictionary. If not - you need to use dictionary of lists (as already suggested)

    0 讨论(0)
提交回复
热议问题