How to add elements in list which is value of dictionary and those elements not be repeated as another keys of that dictionary?
You can group your words by the count of letters using the Counter object:
from collections import Counter
from itertools import groupby
sorted list = sorted(anList, key=Counter)
groups = [list(y) for x, y in groupby(sortedList, key=Counter)]
#[['aba', 'baa', 'aab'], ['cat', 'tac', 'act'], ['sos', 'oss']]
Now, convert the list of lists of anagrams into a dictionary:
{words[0]: words[1:] for words in groups}
#{'aba': ['baa', 'aab'], 'cat': ['tac', 'act'], 'sos': ['oss']}
The answers from @DYZ and @AnttiHaapala handle the expected output posted in the question much better than this one.
Following is an approach that comes with some caveats using collections.defaultdict
. Sort each list element to compare it to the anagram key and append any anagrams that are not the same as the key.
from collections import defaultdict
anagrams = ['aba','baa','aab','cat','tac','act','sos','oss']
d = defaultdict(list)
for a in anagrams:
key = ''.join(sorted(a))
if key != a:
d[key].append(a)
print(d)
# {'aab': ['aba', 'baa'], 'act': ['cat', 'tac'], 'oss': ['sos']}
Caveats:
- always uses the ascending sorted version of the anagram as the dict key, which is not an exact match for the example output in the question
- if the ascending sorted version of the anagram is not in the list, this approach will add a previously non-existent anagram as the dict key
You can use the function groupby()
on a presorted list. The function sorted
(or Counter
) can be used as the key for sorting and grouping:
from itertools import groupby
anList = ['aba', 'baa', 'aab', 'cat', 'tac', 'act', 'sos', 'oss']
{k: v for _, (k, *v) in groupby(sorted(anList, key=sorted), key=sorted)}
# {'aba': ['baa', 'aab'], 'cat': ['tac', 'act'], 'sos': ['oss']}