w3resource

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:

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:

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.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/python-exercises/extended-data-types/python-extended-data-types-index-ordereddict-exercise-10.php