Anagram Groups By Sorted Keys

Sort each word letters into a canonical key so anagrams land in the same bucket, then aggregate with defaultdict and rank groups by size.

PythonData Integrity

Code

pythonsnippet
17 lines
from collections import defaultdict

words = ["listen", "silent", "enlist", "google", "banana", "gooegl"]

def anagram_key(word):
    """Same multiset of letters sorts into the same canonical key."""
    return "".join(sorted(word))

groups = defaultdict(list)
for word in words:
    groups[anagram_key(word)].append(word)

for key, members in sorted(groups.items()):
    print(f"{key}: {members}")

print("group count:", len(groups))
print("largest group:", max(groups.values(), key=len))

Output

Captured from a sandboxed run of this snippet in the build pipeline.

aaabnn: ['banana']
eggloo: ['google', 'gooegl']
eilnst: ['listen', 'silent', 'enlist']
group count: 3
largest group: ['listen', 'silent', 'enlist']

Inside the logic

Structurally, expect the function anagram_key and nothing else.

The cycling part of this snippet is for word in words.

What to watch for

  • Runs on the standard library alone; nothing to install.

Using it

Signature: def anagram_key(word)

The demo output is labeled (group count:, largest group:); each label names the call that printed it.

anagram_key is the public entry point; everything else in the file exists to support it.

Key statements

def anagram_key(word):
    """Same multiset of letters sorts into the same canonical key."""
    return "".join(sorted(word))

Interactive Tools for This Topic

FAQ

Do I need to install anything before running this?
No — every API used here ships with the language runtime, so there is nothing to install. Every import resolves inside the standard library — `collections`. The file defines `anagram_key` at load time.