Iteration

4 / 5

A Python dictionary is very similar to a list. Where lists use integers as indexes, dictionaries use strings as indexes. The string index of a dictionary is called the key. The thing that keys refer to are called the value. Dictionaries are just a collection of key-value pairs, where every key is unique. Among many other things, dictionaries are great data structures for histograms: counting how many times things occur.

fruit_supply = { 'apple' => 5, 'banana' => 3, 'coconut' => 3, 'fig' => 4}
print(fruit_supply['fig']) # output: 4
print(fruit_supply['lime']) # output: KeyError, dictionary has no key 'lime'

It is possible to add new key entries in existing dictionaries:

if 'lime' not in fruit_supply:
  # create new entry for 'lime'
  fruit_supply['lime'] = 0

The empty dictionary is just {}.

Dictionaries

In the code below, the input string s is split into a list of all the words in s, separated by spaces. Starting with an empty dictionary, count how many times a word occurs in words. Print the resulting dictionary.

Congratulations!

You passed the !

Welcome!

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

Your email has been verified!