dictionary with tuple keys
John Machin
sjmachin at lexicon.net
Tue Dec 15 03:33:22 EST 2009
Ben Finney <ben+python <at> benfinney.id.au> writes:
> In this case, I'll use ‘itertools.groupby’ to make a new sequence of
> keys and values, and then extract the keys and values actually wanted.
Ah, yes, Zawinski revisited ... itertools.groupby is the new regex :-)
> Certainly it might be clearer if written as one or more loops, instead
> of iterators. But I find the above relatively clear, and using the
> built-in iterator objects will likely make for a less buggy
> implementation.
Relative clarity like relative beauty is in the eye of the beholder,
and few parents have ugly children :-)
The problem with itertools.groupby is that unlike SQL's "GROUP BY"
it needs sorted input. The OP's requirement (however interpreted)
can be met without sorting.
Your interpretation can be implemented simply:
from collections import defaultdict
result = defaultdict(list)
for key, value in foo.iteritems():
result[key[:2]].append(value)
More information about the Python-list
mailing list