Write a function filterByLength(WORDS, N) in Python, that takes a dictionary, WORDS and an integer, N as arguments and returns a new dictionary that contains only the key-value pairs whose values have length equal to N. If the dictionary is empty or has no values with length N, return an empty dictionary.

For example, Consider the following dictionary and integer

WORDS = {1:"Apple", 2:"Orange", 3:"Banana", 4:"Grape", 5:"Kiwi"}

N = 5

The output should be:

{1:"Apple", 4:"Grape"}

Answer:

Answer by student

Function in Python that takes a dictionary and an integer as arguments and returns a new dictionary that contains only the key-value pairs whose values have length equal to N - Teachoo.png

Detailed answer by teachoo

To write a function that filters a dictionary by the length of its values, we need to follow these steps:

  • Define a function named filterByLength that takes two parameters: WORDS, which is the dictionary to be filtered, and N, which is the integer that represents the length of the values.
  • Inside the function, create a variable named filtered and assign it an empty dictionary. This variable will store the new dictionary with the key-value pairs that have values with length N.
  • Use a for loop to iterate over the items of the dictionary. We can use the items method to get a list of tuples of (key, value) pairs in the dictionary.
  • In each iteration, check if the length of the value is equal to N using the len function and the == operator. This will ensure that we only select the key-value pairs that match our criteria.
  • If the length of the value is equal to N, add the key-value pair to the filtered dictionary using square brackets and assignment operator. This will add the key-value pair to the new dictionary.
  • After the loop ends, return the filtered dictionary as the output of the function.

The final code is:

Function in Python(with comments) that takes a dictionary and an integer as arguments and returns a new dictionary that contains only the key-value pairs whose values have length equal to N - Teachoo.png

Go Ad-free
Davneet Singh's photo - Co-founder, Teachoo

Made by

Davneet Singh

Davneet Singh has done his B.Tech from Indian Institute of Technology, Kanpur. He has been teaching from the past 14 years. He provides courses for Maths, Science, Social Science, Physics, Chemistry, Computer Science at Teachoo.