Python version of STL multimap?

Martin v. Loewis martin at v.loewis.de
Sat Jul 6 17:09:10 EDT 2002


Roy Smith <roy at panix.com> writes:

>    try:
>       dict[key].append (value)
>    except KeyError:
>       dict[key] = [value]
[...]
> So, the question is, is there a standard way in Python to do multimaps, 
> or should I just continue to roll my own with one of the above idioms 
> whenever I need one?

There is no standard data type in Python for multimaps; dictionaries
of lists is the standard idiom. If you want a convenient notation and
can accept creating temporary unused list, you can write it as

  dict.setdefault(key,[]).append(value)

HTH,
Martin




More information about the Python-list mailing list