LearnWave
Learn it. Master it.

Tuples and Dictionaries

Manipulating dictionaries

Count things with a dictionary.

The book's programs show how dictionaries are used:

  • Program 10-5 works with ODD = {1:'One', 3:'Three', 5:'Five', 7:'Seven', 9:'Nine'}: it displays the keys(), values() and items(), finds len(ODD), checks membership (7 in ODD is True, 2 in ODD is False), looks up ODD.get(9) ('Nine'), and deletes an item with del.
  • Program 10-6 reads employees' names and salaries into a dictionary, with the name as the key: employee[name] = salary. Then it prints them as a table.
  • Program 10-7 counts how often each character appears in a string. For each character ch: if ch is already a key, add 1 to its count; otherwise, set its count to 1. For 'banana', the result is b : 1, a : 3, n : 2.
  • Program 10-8 turns a number into words, using numberNames = {0:'Zero', 1:'One', …, 9:'Nine'}. Each digit is looked up in turn: 6512 becomes Six Five One Two.

The pattern to remember: use a dictionary whenever something must be looked up or counted by a key. 'Key → count' is the most common pattern of all.

Key → count is the most common pattern.

Practise this lesson

Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.

No account, no email address. Opens the real product.