Previous

Iteration

4 / 5
Next

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 {}.

Send

Dictionaries

Hint
Hard

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.

Help
Solve
Reset
Run
Submit
 

Test results

Test result #
Expected output
Your output

Your email has been verified!