Suppose I have one list which contains anagram strings. For example,
anList = ['aba','baa','aab','cat','tac','act','sos','oss']
And I want to construct a dictionary which contains element of that list as key and anagram strings of that element will be values of that key as a list, Also elements which will be added into list are not repeated as another key of that dictionary. For example, if 'baa' has added to list, which list is value of key 'aba', then 'baa' can not be added as key further. Output dictionary should be look like,
anDict = {'aba' : ['baa','aab'],'cat' : ['tac','act'],'sos' : ['oss']}
I have tried with many approaches, but problem is that added elements in list are again add as key of dictionary.
How can I done it?
By using ” + ” operator we can append the lists of each key inside a dictionary in Python.
To convert dictionary values to list sorted by key we can use dict. items() and sorted(iterable) method. Dict. items() method always returns an object or items that display a list of dictionaries in the form of key/value pairs.
Appending element(s) to a dictionary To append an element to an existing dictionary, you have to use the dictionary name followed by square brackets with the key name and assign a value to it.
It definitely can have a list and any object as value but the dictionary cannot have a list as key because the list is mutable data structure and keys cannot be mutable else of what use are they.
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']}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With