Python function for word lengths OrderedDict
Write a Python function that takes a list of words and returns an OrderedDict where keys are the words and values are the lengths of the words.
Sample Solution:
Code:
from collections import OrderedDict
def word_lengths_ordered_dict(words):
ordered_dict = OrderedDict()
for word in words:
ordered_dict[word] = len(word)
return ordered_dict
def main():
words = ["Red", "Green", "Pink", "White", "Orange"]
result = word_lengths_ordered_dict(words)
for word, length in result.items():
print(f"{word}: {length}")
if __name__ == "__main__":
main()
Output:
Red: 3 Green: 5 Pink: 4 White: 5 Orange: 6
In the exercise above, the "word_lengths_ordered_dict()" function iterates through the list of words and adds each word as a key to the 'OrderedDict', with its corresponding length as the value. The "main()" function prints each word along with its length from the generated 'OrderedDict' using the "word_lengths_ordered_dict()" function.
Flowchart:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics