Dev Helpers
← Back

Bucket words by their sorted letter signature

Bucket words by their sorted letter signature using Python lists and dictionaries.

Open this example in the interactive library

Source code

from collections import defaultdict
groups = defaultdict(list)
for word in ['tea', 'tan', 'eat', 'ant']:
    groups[''.join(sorted(word))].append(word)
print(list(groups.values()))

Sample output

[['tea', 'eat'], ['tan', 'ant']]