How can I use python itertools.groupby() to group a list of strings by their first character?

19,683

Solution 1

groupby(sorted(tags), key=operator.itemgetter(0))

Solution 2

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])}

Solution 3

>>> for i, j in itertools.groupby(tags, key=lambda x: x[0]):
    print(i, list(j))


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

Solution 4

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']})
Share:
19,683
Adam Ziolkowski
Author by

Adam Ziolkowski

I make websites.

Updated on June 14, 2022

Comments

  • Adam Ziolkowski
    Adam Ziolkowski almost 2 years

    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()?