- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character
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 −
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.
Advertisements