words = ['apple', 'banana', 'avocado', 'berry', 'cherry', 'apricot']
word_dict = {}
for word in words:
first_char = word[0].lower()
if first_char in word_dict:
word_dict[first_char].append(word)
else:
word_dict[first_char] = [word]
print("Dictionary with first character as key:", word_dict)
#source code --> clcoding.com
Code Explanation:
Input List:
words = ['apple', 'banana', 'avocado', 'berry', 'cherry', 'apricot']
This is the list of words that we want to group based on their first characters.
Create an Empty Dictionary:
word_dict = {}
This dictionary will hold the first characters of the words as keys and lists of corresponding words as values.
Iterate Through the Words:
for word in words:
The loop goes through each word in the words list one by one.
Extract the First Character:
first_char = word[0].lower()
word[0] extracts the first character of the current word.
.lower() ensures the character is in lowercase, making the process case-insensitive (useful if the words had uppercase letters).
Check if the First Character is in the Dictionary:
if first_char in word_dict:
This checks if the first character of the current word is already a key in word_dict.
Append or Create a New Key:
If the Key Exists:
word_dict[first_char].append(word)
The current word is added to the existing list of words under the corresponding key.
If the Key Does Not Exist:
word_dict[first_char] = [word]
A new key-value pair is created in the dictionary, where the key is the first character, and the value is a new list containing the current word.
Output the Dictionary:
print("Dictionary with first character as key:", word_dict)
This prints the resulting dictionary, showing words grouped by their first characters.
0 Comments:
Post a Comment