Print anagrams together in Python using List and Dictionary
Last Updated :
11 Feb, 2025
Improve
An anagram is a word or phrase formed by rearranging the letters of another word or phrase, using all the original letters exactly once. The task of grouping anagrams together in Python can be efficiently solved using lists and dictionaries. The key idea is to process each word by sorting its characters, which helps identify anagrams as they will share the same sorted representation. By using a dictionary, we can store these sorted words as keys and group the original words as values, ensuring that all anagrams appear together.
For example, given a list a = ['bat', 'nat', 'tan', 'ate', 'eat', 'tea'], the expected output would be:[['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']].
dict = {} # initialize empty dictionary
a = ['bat', 'nat', 'tan', 'ate', 'eat', 'tea']
# Iterate through each word
for word in a:
sort_word = ''.join(sorted(word))
if sort_word in dict:
dict[sort_word].append(word)
else:
dict[sort_word] = [word]
res = list(dict.values())
print(res)
Output
[['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']]
Explanation:
- sorted(word) arranges the letters of the word in alphabetical order and ''.join(sorted(word)) converts the sorted list of characters back into a string.
- If sort_word is already a key in dict, append the current word to its corresponding
- Otherwise, create a new entry in dict with sort_word as the key and the word as the first element of a new list.
- list(dict.values()) extracts those lists and stores them in res.