-2

How shall I convert a string as given below into a dictionary in the given way?

sentence = "python is a programming language"

Output:

{'p' : ['python', 'programming'], 'i' : ['is'], 'a' : ['a'], 'l' : ['language']}
Pranav Hosangadi
  • 23,755
  • 7
  • 44
  • 70
Dynamite
  • 1
  • 1
  • What you have tried so far? – nobleknight Jun 17 '21 at 18:31
  • I have split the string to convert it into a list, storing that into a new object then I have created an empty dictionary named 'd'. Then while using the for loop i was trying to sort it, but wasn't able to do so – Dynamite Jun 17 '21 at 18:45

1 Answers1

0
sentence = "python is a programming language"
d = {}
for s in sentence.split():
    if s[0] not in d.keys():
        d[s[0]] = [s]
    else:
        d[s[0]].append(s)
Stefan Papp
  • 2,199
  • 1
  • 28
  • 54