Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
A short Python script to print out anagrams.
#!/usr/bin/env python3
./ myword
Prints out a list of anagrams of myword.
This uses the file /usr/share/dict/words to get a dictionary.
# ______________________________________________________________________
# Imports
import sys
from collections import defaultdict
# ______________________________________________________________________
# Functions
def load_wordmap():
""" Load all words and map their sorted string to a list of all the words
that sort to that key. Eg 'aemt' -> ['meat', 'team', ...].
with open('/usr/share/dict/words') as f:
wordlist = [line.strip() for line in f if len(line.strip()) > 0]
# Add approximate plurals.
plurals = [x + 's' if not x.endswith('s') else x + 'es' for x in wordlist]
wordlist += plurals
wordmap = defaultdict(list)
for word in wordlist:
return wordmap
def print_anagrams(wordmap, word):
""" Using `wordmap`, print all the anagrams of `word`. """
for other_word in wordmap[''.join(sorted(word))]:
# ______________________________________________________________________
# Main
if __name__ == '__main__':
if len(sys.argv) == 1:
wordmap = load_wordmap()
print_anagrams(wordmap, sys.argv[1])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment