Create a dictionary of words with the letters sorted
This Python code takes a list of words and creates a dictionary sorted_letters where the keys are words, and the values are the words with their letters sorted in alphabetical order. Here's how the code works:
- words = ['python', 'programming', 'language']: This line initializes a list named words with three words.
- sorted_letters = {word: ''.join(sorted(word)) for word in words}: This line uses a dictionary comprehension to create the sorted_letters dictionary. It iterates through each word word in the words list and assigns a key-value pair to the dictionary. The key is the word itself (word), and the value is the result of the following expression:
- ''.join(sorted(word)): This part of the code sorts the letters in each word alphabetically and joins them back together into a string. The sorted function is used to sort the characters in the word, and join combines the sorted characters into a single string.
- for word in words: This part of the code iterates through each word in the words list.
- print(words): This line prints the original words list to the console.
- print(sorted_letters): This line prints the sorted_letters dictionary, which contains the words as keys and the words with their letters sorted in alphabetical order as values.
Source Code
words = ['python', 'programming', 'language']
sorted_letters = {word: ''.join(sorted(word)) for word in words}
print(words)
print(sorted_letters)
Output
['python', 'programming', 'language']
{'python': 'hnopty', 'programming': 'aggimmnoprr', 'language': 'aaegglnu'}