Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character

PythonServer Side ProgrammingProgramming

When it is required to create a dictionary with the key as the first character and the associated value as the word which is the starting of that character, the s’plit’ method, a dictionary and simple ‘if’ condition is used.

Example

Below is a demonstration for the same −

 Live Demo

my_string=input("Enter the string :")
split_string = my_string.split()
my_dict={}
for elem in split_string:
   if(elem[0] not in my_dict.keys()):
      my_dict[elem[0]]=[]
      my_dict[elem[0]].append(elem)
   else:
      if(elem not in my_dict[elem[0]]):
         my_dict[elem[0]].append(elem)
print("The dictionary created is")
for k,v in my_dict.items():
   print(k,":",v)

Output

Enter the string :Hey Jane, how are you
The dictionary created is
H : ['Hey']
J : ['Jane,']
h : ['how']
a : ['are']
y : ['you']

Explanation

  • The string is taken as input from the user.
  • This is assigned to a variable.
  • This string is split, and assigned to a variable.
  • An empty dictionary is created.
  • The variable is iterated over, and if the first element is not present as a key in the dictionary, its element is assigned an empty list.
  • Now, the elment is added to the dictionary.
  • Otherwise, the element is directly appended to the dictionary.
  • This dictionary is created, and is displayed on the console.
raja
Published on 12-Mar-2021 12:52:48
Advertisements