expression form of one-to-many dict?

Steven Bethard steven.bethard at
Fri Dec 17 22:14:54 CET 2004

So I end up writing code like this a fair bit:

map = {}
for key, value in sequence:
     map.setdefault(key, []).append(value)

This code basically constructs a one-to-many mapping -- each value that 
a key occurs with is stored in the list for that key.

This code's fine, and seems pretty simple, but thanks to generator 
expressions, I'm getting kinda spoiled. ;)  I like being able to do 
something like the following for one-to-one mappings:


or a more likely scenario for me:

     dict((get_key(item), get_value(item) for item in sequence)

The point here is that there's a simple sequence or GE that I can throw 
to the dict constructor that spits out a dict with my one-to-one mapping.

Is there a similar expression form that would spit out my one-to-many 


More information about the Python-list mailing list