Iteration

5 / 5

Like integer ranges and lists, dictionaries are iterable.

fruit_basket = {'apple': 5, 'banana': 3, 'cherry': 10}
for key in fruit_supply:
  print(f"The basket contains pieces of {key}")

This code runs over all keys in the dictionary and prints:

The basket contains pieces of apple
The basket contains pieces of banana
The basket contains pieces of cherry

In order to get both key and value, use the items method of the dictionary class:

fruit_basket = {'apple': 5, 'banana': 3, 'cherry': 10}
for key,val in fruit_supply.items():
  print(f"There are {val} pieces of {key} in the basket")

This code runs over all key-value pairs in the dictionary and prints:

There are 5 pieces of apple in the basket
There are 3 pieces of banana in the basket
There are 10 pieces of cherry in the basket

Dictionary iteration

Write a function longest_frequent with one parameter word_hist that is a histogram of words (as a dictionary). The function should return the longest word that occurs at least 5 times.

For example, if d = {'love': 5, 'peace': 4, 'joy': 7} then most_frequent(d) must return love.

Congratulations!

You passed the !

Welcome!

Would you like a guided tour on how to use Vibewise?

Your email has been verified!