Start free

A level · 8 exercises

Python dictionaries

A dictionary links keys to values, like words to meanings: ages["Ann"] = 12. Looking up a key is fast, however big it is.

.get(key, 0) gives a default when the key isn't there; looping over a dictionary gives its keys, .items() gives keys and values together.

counts = {}
for word in input().split():
    counts[word] = counts.get(word, 0) + 1
for word, n in counts.items():
    print(word, n)

Watch for: Reading a key that isn't there stops the program with a KeyError: check with in, or use .get().

Exercises

  1. Word frequencyCount how often each word appears (ignore capital letters).Intermediate
  2. Letter chartCount the letters in a line (ignore capitals, spaces and punctuation) and draw a barIntermediate
  3. Phone bookRead a phone book, then answer questions about it.Intermediate
  4. AnagramsTwo words are anagrams when they use exactly the same letters, like listen andIntermediate
  5. Group by first letterGroup words by their first letter.Intermediate
  6. Average per studentRead scores; a student can appear several times.Intermediate
  7. Stock countA shop records deliveries (positive) and sales (negative).Intermediate
  8. First unique letterFind the first character that appears only once in a word.Intermediate
Start with “Word frequency”