Atif Imam Atif Imam - 3 months ago 19
Python Question

From a sentence group all words that start with same alphabet and and sort it a/q to first character of the word

suppose I take a string input from the user , and if will then group all the words in that sentence with respect to first character of the word and later we have to display the o/p as dictionary , No repetition of words is allowed .
For example consider i/p string

a="A cat ran after the dog and died due to injury"


Then o/p should be :

{'A': ['A'], 'a': ['after', 'and'], 'c': ['cat'], 'd': ['died', 'dog', 'due'], 'i': ['injury'], 'r': ['ran'], 't': ['the', 'to']}


Here is making list according to starting character and all the words starting with that character .
I have made this program :

a="A cat ran after the dog and died due to injury"
b=[]
c={}
b=list(sorted(set(a.split())))
for x in b:
e=x[0]
c.setdefault(e,[])
c[e].append(x)
print (c)


Can you suggest me different way to do this . I am not satisfied with this approach of mine . Please provide a algorithmic way .
The language I am using is python3

Answer

You could simplify your code a little but apart from that it's ok

from collections import defaultdict
a="A cat ran after the dog and died due to injury"
c=defaultdict(list)

for x in set(a.split()):  # no need to sort unless you create an OrderedDict which you didn't
    c[x[0]].append(x)
print (c)

You can replace the loop by

any(map(lambda x : c[x[0]].append(x),set(a.split())))
Comments