PythonMastery
Python programs · Useful programs · intermediate

Group anagrams in Python

Put words that are anagrams of each other, like listen and silent, into groups, using the sorted letters of each word as a dictionary key.

Two words are anagrams when they use exactly the same letters, like "listen" and "silent". If you sort the letters of each word, all anagrams give the same result, so the sorted letters make a good dictionary key for each group.

The program

python
from collections import defaultdict

words = ["listen", "silent", "enlist", "google", "tea", "eat", "Ate", "bat", "tab", "python"]

groups = defaultdict(list)
for word in words:
    key = "".join(sorted(word.lower()))
    groups[key].append(word)

for key, group in groups.items():
    print(f"{key:8} {group}")
output
eilnst   ['listen', 'silent', 'enlist']
eggloo   ['google']
aet      ['tea', 'eat', 'Ate']
abt      ['bat', 'tab']
hnopty   ['python']

How it works

Only the real groups

Words with no anagram partner, like "google" and "python", form groups of one. To keep only the groups with two or more words:

python
from collections import defaultdict

words = ["listen", "silent", "enlist", "google", "tea", "eat", "Ate", "bat", "tab", "python"]

groups = defaultdict(list)
for word in words:
    groups["".join(sorted(word.lower()))].append(word)

anagram_groups = [group for group in groups.values() if len(group) > 1]
print(anagram_groups)
output
[['listen', 'silent', 'enlist'], ['tea', 'eat', 'Ate'], ['bat', 'tab']]

Learn the idea: Dictionaries, collections: The Stdlib's Hidden Power