Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python Program to Create a Dictionary with Key as First Character and Value as Words Starting with that Character
When you need to group words by their first character, you can create a dictionary where keys are first characters and values are lists of words starting with that character. This uses the split() method, dictionary operations, and conditional logic.
Example
Below is a demonstration for the same ?
my_string = "Hey Jane how are you doing today"
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)
The output of the above code is ?
The dictionary created is: H : ['Hey'] J : ['Jane'] h : ['how'] a : ['are'] y : ['you'] d : ['doing'] t : ['today']
Using defaultdict for Cleaner Code
You can simplify the logic using defaultdict from the collections module ?
from collections import defaultdict
my_string = "apple banana cherry apricot blueberry"
words = my_string.split()
my_dict = defaultdict(list)
for word in words:
if word not in my_dict[word[0]]:
my_dict[word[0]].append(word)
print("The dictionary created is:")
for key, value in sorted(my_dict.items()):
print(key, ":", value)
The dictionary created is: a : ['apple', 'apricot'] b : ['banana', 'blueberry'] c : ['cherry']
How It Works
- The input string is split into individual words using
split() - An empty dictionary is created to store the results
- For each word, the first character
elem[0]becomes the key - If the key doesn't exist, create an empty list and add the word
- If the key exists, check for duplicates before adding the word
- The final dictionary groups words by their starting character
Conclusion
This approach efficiently groups words by their first character using dictionary operations. The defaultdict method provides cleaner code by automatically handling missing keys.
Advertisements
