Create a dictionary of words and their first letter capitalized
The List of words and creates a dictionary named capitalized_first_letter. This dictionary maps each word to a version of the word where the first letter is capitalized. Here's how the code works:
- words = ['apple', 'banana', 'cherry']: This line initializes the words variable with a list of words.
- capitalized_first_letter = {word: word[0].upper() + word[1:] for word in words}: This line uses a dictionary comprehension to create the capitalized_first_letter dictionary. It iterates through each word in the words list.
- {word: word[0].upper() + word[1:]}: This part of the code creates key-value pairs in the dictionary. The key is the original word, and the value is a modified version of the word where the first letter is capitalized. This is achieved by using word[0].upper() to capitalize the first letter and then concatenating it with the rest of the word obtained using word[1:]
- print(words): This line prints the original list of words, words, to the console.
- print(capitalized_first_letter): This line prints the capitalized_first_letter dictionary, which contains the original words as keys and their versions with the first letter capitalized as values.
Source Code
words = ['apple', 'banana', 'cherry']
capitalized_first_letter = {word: word[0].upper() + word[1:] for word in words}
print(words)
print(capitalized_first_letter)
Output
['apple', 'banana', 'cherry']
{'apple': 'Apple', 'banana': 'Banana', 'cherry': 'Cherry'}