pk.
pk.

Reputation: 99

I am writing a program to find the anagrams from a list of words and output the anagrams in different lists but in an alphabetical order

some_list = ['bad', 'app', 'sad', 'mad', 'dab','pge', 'bda', 'ppa', 'das', 'dba']

new_list = []
from collections import OrderedDict
for ele in OrderedDict.fromkeys("".join(sorted(ele)) for ele in some_list):
    temp = []
    for s in some_list:
        if ele == ''.join(sorted(s)):
            temp.append(s)
    if len(temp) > 1:
        new_list.append(temp)

for i in new_list:
    i.sort()
    print(i)

The output is:

I want the output to be:

How do I change the code to get the right output?

Upvotes: 2

Views: 109

Answers (2)

Padraic Cunningham
Padraic Cunningham

Reputation: 180481

sort before you create the words:

from collections import OrderedDict
some_list.sort()
for ele in OrderedDict.fromkeys("".join(sorted(ele)) for ele in some_list):
   ...........

Upvotes: 1

Bhargav Rao
Bhargav Rao

Reputation: 52151

sort your new_list before printing using sorted

for i in sorted(new_list):
    i.sort()
    print(i)

This will print your output as expected

Upvotes: 4

Related Questions