Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 264
Ishan Trivedi Avatar asked May 05 '19 04:05

Ishan Trivedi


People also ask

How do you append to a list that is a value in a dictionary Python?

By using ” + ” operator we can append the lists of each key inside a dictionary in Python.

How do I put all the values in a dictionary into a list?

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.

How do I add elements to an existing dictionary?

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.

Is it possible to place a list as a value inside the dictionary?

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.


Video Answer


1 Answers

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']}
like image 92
DYZ Avatar answered Oct 19 '22 13:10

DYZ