by BehindJava
Write a program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character in Python
In this tutorial we are going to learn about creating a Dictionary with Key as First Character and Value as Words Starting with that Character in Python.
Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character
test_string=raw_input("Enter string:")
l=test_string.split()
d={}
for word in l:
if(word[0] not in d.keys()):
d[word[0]]=[]
d[word[0]].append(word)
else:
if(word not in d[word[0]]):
d[word[0]].append(word)
for k,v in d.items():
print(k,":",v)
Explanation
- User must enter a string and store it in a variable.
- An empty dictionary is declared.
- The string is split into words and is stored in a list.
- A for loop is used to traverse through the words in the list.
- An if statement is used to check if the word already present as a key in the dictionary.
- If it is not present, the letter of the word is initialized as the key and the word as the value, and they are appended to a sublist created in the list.
- If it is present, the word is added as the value to the corresponding sublist.
- The final dictionary is printed.