Python version of STL multimap?
Boudewijn Rempt
boud at valdyas.org
Sat Jul 6 17:21:55 EDT 2002
Roy Smith wrote:
> 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]
>
<...>
> 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?
Isn't this exactly what Alex Martelli posted the other day:
dict.setdefault(key, []).append(value)
in answer to the thread about sorting a dictionary by its value?
--
Boudewijn Rempt | http://www.valdyas.org
More information about the Python-list
mailing list