S
Steven Bethard
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:
dict(sequence)
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
mapping?
Steve
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.
something like the following for one-to-one mappings:
dict(sequence)
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
mapping?
Steve