From Chen's Wiki

Jump to: navigation, search

Problem

You have a list like:

phone_number = [('john', 123), ('mike', 321), ('john', 213)]

which is fairly common that John has a number for office and one for his cell phone.

Solution

Quite a lot, I recommend making a subclass of the default dict and overwrite the __setitem__ method.

class DupDict(dict):
	def __setitem__(self, key, value):
		try:
			self[key]
		except KeyError:
			super(DupDict, self).__setitem__(key, [])
		self[key].append(value)

#example
db = reduce(returnable, data, DupDict())

Done. I'd like to add some functional flavor into it. The messy thing is that for Python dict (or in the concept of dictionary), setting a new key value will return nothing. Then I have to do something like this:

def returnable(d, pair):
    d.__setitem__(*pair)
    return d