How to add elements in list which is value of dictionary and those elements not be repeated as another keys of that dictionary?

Related searches

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?

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']}

Manipulating Lists and Dictionaries in Python, Of course, we can add that key and its corresponding value as a new element to the dictionary. To do that, we will use the .update() method as� Examples. The following code example creates an empty Dictionary<TKey,TValue> of strings with string keys and uses the Add method to add some elements. The example demonstrates that the Add method throws an ArgumentException when attempting to add a duplicate key.

Here combining both the order of occurrence with the possibility of them not being grouped together:

anagram_list = ['cat','aba','baa','aab','tac','sos','oss','act']

first_anagrams = {}
anagram_dict = {}

for word in anagram_list:
    sorted_word = ''.join(sorted(word))
    if sorted_word in first_anagrams:
        anagram_dict[first_anagrams[sorted_word]].append(word)
    else:
        first_anagrams[sorted_word] = word
        anagram_dict[word] = []

print(anagram_dict)

The output is

{'aba': ['baa', 'aab'], 'sos': ['oss'], 'cat': ['tac', 'act']}

where the key is always the first anagram in order of occurrence, and the algorithm is strictly O(n) for n words of neglible length.


Should you want all anagrams in the list including the first one, it becomes much easier:

anagram_list = ['cat','aba','baa','aab','tac','sos','oss','act']

first_anagrams = {}
anagram_dict = defaultdict(list)

for word in anagram_list:
    anagram_dict[first_anagrams.setdefault(''.join(sorted(word)), word)].append(word)

The result is

defaultdict(<type 'list'>, 
    {'aba': ['aba', 'baa', 'aab'], 'sos': ['sos', 'oss'], 'cat': ['cat', 'tac', 'act']})

20. Dictionaries — How to Think Like a Computer Scientist: Learning , Another way to create a dictionary is to provide a list of key:value pairs using the The values in a dictionary are accessed with keys, not with indices, so there is � In this tutorial, learn how to add an element to key in Dictionary with Python. You can also append the new element to the existing key or add multiple key pairs. Update the existing key value for the accuracy of Dictionary elements. The dictionary is the collection of unordered elements in Python.

Python Dictionary, keys inside a dictionary can't have duplicates, but their values can repeat themselves. If you wish to create a Python dictionary with fixed keys and values , then it's return a KeyError while the latter returns None if the element is not available. Another example of creating a dictionary from the list of weekdays as keys� ''' Converting a list to dictionary with list elements as keys in dictionary using dict.fromkeys() ''' dictOfWords = dict.fromkeys(listOfStr , 1) dict.fromKeys() accepts a list and default value. It returns a dictionary with items in list as keys. All dictionary items will have same value, that was passed in fromkeys().

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']}

Python Dictionaries, It covers how to create a dictionary, how to access its elements, delete elements, of the index we use keys to access the elements of a dictionary (or values to the reverse is not true, which means that elements can be repeated, but key For example, let's assume that there is another dictionary containing the list of the � Dictionaries are written with curly brackets, and they have keys and values. It is used to hash a particular key. A dictionary has multiple key:value pairs. There can be multiple pairs where value corresponding to a key is a list. To check that the value is a list or not we use the isinstance() method which is inbuilt in Python.

Here is slow, but working code:

anList = ['aba', 'baa', 'aab', 'cat', 'tac', 'act', 'sos', 'oss']
anDict = {}
for i in anList:
    in_dict = False
    for j in anDict.keys():
        if sorted(i) == sorted(j):
            in_dict = True
            anDict[j].append(i)
            break
    if not in_dict:
        anDict[i] = []

Dictionaries in Python – Real Python, Python provides another composite data type called a dictionary, which is List elements are accessed by their position in the list, via indexing. Adding an entry to an existing dictionary is simply a matter of assigning a new key and Just as the values in a dictionary don't need to be of the same type, the keys don't either:. Now, let’s see different ways of creating a dictionary of list. Note that the restriction with keys in Python dictionary is only immutable data types can be used as keys, which means we cannot use a dictionary of list as a key .

A dictionary variable can store another dictionary in nested dictionary. The following example shows how nested dictionary can be declared and accessed using python. Here, ‘courses’ is a nested dictionary that contains other dictionary of three elements in each key. Next, for loop is used to read the value of each key of the nested dictionary.

A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.

Accessing elements of a dictionary. Elements stored in a dictionary can be accessed just like lists in python, i.e, using the for loop. However, while iterating over each element, we will get the key and not the value of the element, therefore, to access the value of the element, we have to use the key just like index, For example: myDictionary[key].

Comments
  • Can your list have any repeating elements?
  • No, there is no repeating elements in list. @Ayxan
  • Are the anagram-groups always adjacent to each other? (e.g. is ['aba','baa','aab','cat','tac','sos','act','oss'] possible?)
  • What! Didn't know that a datatype like Counter can be used as a key!
  • @DeveshKumarSingh It is used as a sorting key, not as a dictionary key. All anagrams by definition have the same letter counter.
  • Yes I actually meant to say sorting key! Okay since they have same letter counter it groups them accordingly
  • Yes It works perfectly fine, But there is one issue. If these anagram words are not adjacent to each other in list, then it will add new keys for those nonadjacent words even if they are anagram to each other.
  • Sorry, the list must be sorted first. Check the updated answer.
  • And this would fail if it was sos, sso
  • @AnttiHaapala - good point, 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 (resulting in more keys / values than there were elements in the original list).
  • @TrebledJ I thought about sets as well. But if there are words, which have different numbers of equal letters, you get a problem.