Python version of STL multimap?

Roy Smith roy at panix.com
Sat Jul 6 16:42:38 EDT 2002


I often want to create a dictionary whose values are lists of items with 
the same key.  I've got variations on:

   if dict.has_key (key):
      dict[key].append (value)
   else:
      dict[key] = [value]

sprinkled throughout my code in many places.  Sometimes I write it as:

   try:
      dict[key].append (value)
   except KeyError:
      dict[key] = [value]

In a parallel universe, I recently decided it was about time to finally 
learn STL, so I picked up a book on it.  Lo and behold, there's the 
multimap container template.  Exactly what I've been doing in Python 
without knowing the right name for it.

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?



More information about the Python-list mailing list