Python multimap

Carl Banks pavlovevidence at gmail.com
Thu Aug 28 00:19:15 EDT 2008


On Aug 27, 1:52 pm, brad <byte8b... at gmail.com> wrote:
> Mike Kent wrote:
> > Python 2.5.2 (r252:60911, Jul 31 2008, 17:28:52)
> > [GCC 4.2.3 (Ubuntu 4.2.3-2ubuntu7)] on linux2
> > Type "help", "copyright", "credits" or "license" for more information.
> >>>> k = {}
> >>>> k['1'] = []
> >>>> k['1'].append('Tom')
> >>>> k['1'].append('Bob')
> >>>> k['1'].append('Joe')
>
> >>>> k['1']
> > ['Tom', 'Bob', 'Joe']
>
> There is only one '1' key in your example. I need multiple keys that are
> all '1'. I thought Python would have something built-in to handle this
> sort of thing.
>
> I need a true multimap:
>
> k['1'] = 'Tom'
> k['1'] = 'Tommy'
>
> without Tommy overwriting Tom and without making K's value a list of
> stuff to append to. That's still just a regular map.

What would you want to happen if you were to execute "print k['1']"?


Best I can tell, you want some sort of association list like this:

k = []
k.append(("1","Tom"))
k.append(("1","Tommy"))

which you can iterate through like this:

for key,value in k:
    ....

And if you need to retrieve items with a certain "key", probably it's
easiest to maintain sorted invariant, and to do insertion and lookup
with bisection algorithm (see bisect module).

I don't know of any class in the standard library that does all that
for you though.


Out of curiosity, what does a true multimap solve that a dictionary of
lists not solve?


Carl Banks



More information about the Python-list mailing list