Drew Drew - 1 year ago 70
Python Question

Using Python dict comprehension to index list of words by first letter

Conceptually, this is pretty easy, but I can't seem to figure it out.

I want to turn a list of strings into a dict with each key being the first letter of the list of words associated with it.

# My list of sounds
sounds = ['sniff', 'bark', 'bork', 'blork', 'heck', 'borf', 'bjork', 'boo', 'bre', 'bore']

# My dict comprehension which isn't working
indexed = {s[0]: [s] for s in sounds}

My output look like this:

{'h': ['heck'], 's': ['sniff'], 'b': ['bore']}

I'm missing an append function here, but each time I try to implement it fails to give me the correct output, or it throws a SyntaxError. What am I missing?

Answer Source

No problem, itertools to the rescue. You can group the elements by their first letter, then create a dict out of them.

sounds = ['sniff', 'bark', 'bork', 'blork', 'heck', 'borf', 'bjork', 'boo', 'bre', 'bore']
import itertools

grouped = itertools.groupby(sorted(sounds), key=lambda x: x[0])
d = {k: list(v) for k,v in grouped}