Is there a 'multimap' implementation in Python?

Viewed 44477

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']
7 Answers

You can take list of tuples and than can sort them as if it was a multimap.

listAsMultimap=[]

Let's append some elements (tuples):

listAsMultimap.append((1,'a'))
listAsMultimap.append((2,'c'))
listAsMultimap.append((3,'d'))
listAsMultimap.append((2,'b'))
listAsMultimap.append((5,'e'))
listAsMultimap.append((4,'d'))

Now sort it.

listAsMultimap=sorted(listAsMultimap)

After printing it you will get:

[(1, 'a'), (2, 'b'), (2, 'c'), (3, 'd'), (4, 'd'), (5, 'e')]

That means it is working as a Multimap!

Please note that like multimap here values are also sorted in ascending order if the keys are the same (for key=2, 'b' comes before 'c' although we didn't append them in this order.)

If you want to get them in descending order just change the sorted() function like this:

listAsMultimap=sorted(listAsMultimap,reverse=True)

And after you will get output like this:

[(5, 'e'), (4, 'd'), (3, 'd'), (2, 'c'), (2, 'b'), (1, 'a')]

Similarly here values are in descending order if the keys are the same.

Related