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
sorted(word.lower())gives a list of the letters in alphabetical order:sorted("tea")is['a', 'e', 't']."".join(...)turns that list back into the string"aet".word.lower()comes first, so "Ate" goes into the same group as "tea" and "eat".groupsis adefaultdict(list). When a key is used for the first time, it starts with an empty list, sogroups[key].append(word)works without checking whether the key exists.- A dictionary keeps keys in the order they were first added, so the groups print in the order their first word appeared.
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']]