I have a list of strings similar to this list:
tags = (\'apples\', \'apricots\', \'oranges\', \'pears\', \'peaches\')
How should I go about
groupby(sorted(tags), key=operator.itemgetter(0))
You might want to create dict
afterwards:
from itertools import groupby
d = {k: list(v) for k, v in groupby(sorted(tags), key=lambda x: x[0])}
>>> for i, j in itertools.groupby(tags, key=lambda x: x[0]):
print(i, list(j))
a ['apples', 'apricots']
o ['oranges']
p ['pears', 'peaches']
just another way,
>>> from collections import defaultdict
>>> t=defaultdict(list)
>>> for items in tags:
... t[items[0]].append(items)
...
>>> t
defaultdict(<type 'list'>, {'a': ['apples', 'apricots'], 'p': ['pears', 'peaches'], 'o': ['oranges']})