Table of Contents
To group anagrams in Python, compute a key for each word that depends on which letters it contains and how often each letter appears. Put words with the same key in the same dictionary bucket. Sorting characters is the simplest key. For lowercase English letters, a 26-element count tuple avoids the sort.

“Supersonic” and “percussion” contain the same letters with the same counts.
Method 1: Use sorted characters as the key
from collections import defaultdict
def group_anagrams(words):
groups = defaultdict(list)
for word in words:
key = ''.join(sorted(word))
groups[key].append(word)
return list(groups.values())
words = ['yo', 'act', 'flop', 'tac', 'foo', 'cat', 'oy', 'olfp']
print(group_anagrams(words))
# [['yo', 'oy'], ['act', 'tac', 'cat'], ['flop', 'olfp'], ['foo']]
For example, act, tac, and cat all produce act. The groups appear in the order in which their keys first occur, and each group preserves the input order. Sorting each word of length n takes up to O(n log n) time.
Method 2: Count letters for a fixed alphabet
def group_lowercase_anagrams(words):
groups = defaultdict(list)
for word in words:
counts = [0] * 26
for letter in word:
index = ord(letter) - ord('a')
if not 0 <= index < 26:
raise ValueError('Expected lowercase ASCII letters a–z')
counts[index] += 1
groups[tuple(counts)].append(word)
return list(groups.values())
Counting takes O(n + 26) time per word under the usual fixed-alphabet assumptions. Keep the counts. A set of letters would incorrectly group aab with abb. Another counting idea gives each letter a prime and multiplies the primes. Python integers grow with that product, so multiplication doesn’t stay constant-time as words grow.
Decide what should count as a match
As written, the sorting method distinguishes case, spaces, punctuation, and Unicode code points. For case-insensitive phrases, decide which characters to keep and normalize consistently before generating either key. Test repeated letters, an empty string, and a word without a partner. Review Python dictionaries, sets, and tuples if you want to see why a tuple works as a dictionary key.
Reader Comments 0
Sign in with email or Google to join the discussion.