Python multimap

Michele Petrazzo michele.petrazzo at TOGLIunipex.it
Wed Aug 27 10:12:29 EDT 2008


brad wrote:
> Recently had a need to us a multimap container in C++. I now need to 
> write equivalent Python code. How does Python handle this?
> 
> k['1'] = 'Tom'
> k['1'] = 'Bob'
> k['1'] = 'Joe'
> ....
> 
> Same key, but different values. No overwrites either.... They all must 
> be inserted into the container
> 

Subclassing the builtin dict?

class d(dict):
  def __setitem__(self, item, value):
   if not item in self: super(d, self).__setitem__(item, [])
   self[item].append(value)

 >>> D = d()
 >>> D[1] = "Hello"
 >>> D[1] = "World!"
 >>> D[1]
['Hello', 'World!']


> Thanks,
> Brad

Michele



More information about the Python-list mailing list