Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 219
Adam Ziolkowski Avatar asked Mar 18 '10 17:03

Adam Ziolkowski


2 Answers

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])}
like image 101
Pratik Deoghare Avatar answered Oct 12 '22 12:10

Pratik Deoghare


groupby(sorted(tags), key=operator.itemgetter(0))
like image 38
Ignacio Vazquez-Abrams Avatar answered Oct 12 '22 13:10

Ignacio Vazquez-Abrams