Print Anagrams together in Python using List and Dictionary (original) (raw)

Given a list of words, the task is to group all anagrams together in Python. Anagrams are words formed by rearranging the letters of another word, using all original letters exactly once. **For example:

**Input: ['bat', 'nat', 'tan', 'ate', 'eat', 'tea']
**Output: [['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']]

Let's explore different methods to group anagrams together using list and dictionary in Python.

Using Counter() from collections

This method groups anagrams based on the frequency of each letter instead of sorting. It’s efficient for longer words because it avoids sorting every string.

Python `

from collections import Counter, defaultdict

a = ['bat', 'nat', 'tan', 'ate', 'eat', 'tea'] res = defaultdict(list)

for word in a: key = tuple(sorted(Counter(word).items())) res[key].append(word)

print(list(res.values()))

`

Output

[['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']]

**Explanation:

Using defaultdict() from collections

This method sorts characters and uses the sorted result as a key to group words automatically.

Python `

from collections import defaultdict

a = ['bat', 'nat', 'tan', 'ate', 'eat', 'tea'] res = defaultdict(list)

for word in a: key = ''.join(sorted(word)) res[key].append(word)

print(list(res.values()))

`

Output

[['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']]

**Explanation:

Using Dictionary

This method groups words by sorting their characters and using the sorted string as a key in a dictionary. All words with the same sorted characters fall under the same group.

Python `

a = ['bat', 'nat', 'tan', 'ate', 'eat', 'tea'] res = {}

for word in a: key = ''.join(sorted(word))
res[key] = res.get(key, []) + [word]

output = list(res.values()) print(output)

`

Output

[['bat'], ['nat', 'tan'], ['ate', 'eat', 'tea']]

**Explanation:

This method uses sorting and groupby() to group anagrams in a single line.

Python `

from itertools import groupby

a = ['bat', 'nat', 'tan', 'ate', 'eat', 'tea'] a.sort(key=lambda x: ''.join(sorted(x))) groups = [list(g) for _, g in groupby(a, key=lambda x: ''.join(sorted(x)))]

print(groups)

`

Output

[['bat'], ['ate', 'eat', 'tea'], ['nat', 'tan']]

**Explanation: