Alex Rivera | Logout

Is there a 'multimap' implementation in Python?

Asked 2009-11-13T21:14:58.843
91

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 library?

To illustrate what I mean by "multimap":

a = multidict()
a[1] = 'a'
a[1] = 'b'
a[2] = 'c'

print(a[1])  # prints: ['a', 'b']
print(a[2])  # prints: ['c']
Edit
Report

1 Answer

3

The standard way to write this in Python is with a dict whose elements are each a list or set. As stephan202 says, you can somewhat automate this with a defaultdict, but you don't have to.

In other words I would translate your code to

a = dict()
a[1] = ['a', 'b']
a[2] = ['c']

print(a[1])  # prints: ['a', 'b']
print(a[2])  # prints: ['c']
answered 2010-11-16T08:26:57.800

Your Answer