views:

251

answers:

4

I have a list of strings similar to this list:

tags = ('apples', 'apricots', 'oranges', 'pears', 'peaches')

How should I go about grouping this list by the first character in each string using itertools.groupby()? How should I supply the 'key' argument required by itertools.groupby()?

+5  A: 
groupby(tags, key=operator.itemgetter(0))
Ignacio Vazquez-Abrams
Does it work for Unicode?
Kimmo Puputti
It works on unicodes. If you're asking if it works on UTF-8 strings, then you should instead be asking when you should decode it to a unicode. The answer, of course, is as soon as it comes in.
Ignacio Vazquez-Abrams
Thanks, it works as expected. I do have a list of tags in multiple languages and I'll be testing the ordering with various translators.
Adam Z.
+1  A: 
>>> for i, j in itertools.groupby(tags, key=lambda x: x[0]):
    print(i, list(j))


a ['apples', 'apricots']
o ['oranges']
p ['pears', 'peaches']
SilentGhost
A: 

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']})
ghostdog74
A: 

You might want to create dict after that

from itertools import *

d = dict((k,list(v)) for k,v in groupby(tags, key=lambda x: x[0]))
TheMachineCharmer