Python function for word lengths OrderedDict

Python OrderedDict Data Type: Exercise-10 with Solution

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:


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__":


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: Python function for word lengths OrderedDict.

Previous: Python generating random ASCII OrderedDict.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

Follow us on Facebook and Twitter for latest update.