Home / Python / Example programs / Dictionaries and sets

Python program: Group words that are anagrams

Put words made of the same letters into groups.

The code

from collections import defaultdict

words = ["listen", "silent", "enlist", "google", "gooegl", "cat", "act", "tac", "dog"]
groups = defaultdict(list)
for w in words:
    groups["".join(sorted(w))].append(w)

for key, group in groups.items():
    print(key, group)

Output

eilnst ['listen', 'silent', 'enlist']
eggloo ['google', 'gooegl']
act ['cat', 'act', 'tac']
dgo ['dog']

How it works

Anagrams have the same letters, so sorting the letters gives the same key for every word in a group. defaultdict(list) starts each new group as an empty list.

Python features used

Learn the ideas behind it in the free lesson Modules & the Standard Library.