Week 6 of 106 hours5 exercises

Week 6: Dictionaries and sets

Look things up by name with dictionaries, count and group data, and remove duplicates with sets.

By the end of this week you can

  • Create and update dictionaries
  • Count and group items
  • Loop over keys, values and pairs
  • Use sets for uniqueness and membership

Dictionaries: look up by key

A dictionary stores pairs: a key and the value it points to, written in curly braces. Where a list is found by position, a dictionary is found by key, so it is perfect for things like a phone book or a student record.

Read with d[key], add or change with d[key] = value, delete with del d[key]. Reading a key that is not there raises a KeyError, so use d.get(key, default) when it might be missing. Keys must be of a fixed type such as text, numbers or tuples.

in checks the keys, not the values.

Looping over a dictionary

Looping over a dictionary gives its keys. Use .values() for the values and .items() for both together; each item arrives as a (key, value) pair that you can unpack in the for line.

Dictionaries remember the order in which keys were added.

Counting and grouping

Dictionaries are the standard tool for counting. For each item, add one to its entry, starting from 0 if it is new. d.get(key, 0) + 1 does that neatly. Grouping works the same way, with lists as the values.

setdefault creates the empty list the first time a key is seen.

Sets: unique values

A set is a collection with no duplicates and no order. Turn a list into a set to remove repeats. Checking membership with in is very fast. Sets also do maths: | is union (everything), & is intersection (only what is in both) and - is difference (in the first but not the second).

To make an empty set write set(); {} on its own is an empty dictionary.

Common mistakes

  • Reading a missing key with d[key]. Use d.get(key) when the key may not exist.
  • Expecting {} to be an empty set. It is an empty dictionary.
  • Using a list as a key. Keys must be unchangeable, so use a tuple instead.
  • Forgetting that looping over a dictionary gives keys only.

Quick recap

  • Dictionaries map keys to values; use get() for safe lookups.
  • Counting is get(key, 0) + 1 in a loop.
  • Sets hold unique values and support union, intersection and difference.
  • Keys must be unchangeable.

Practise this week

Work through the 5 exercises for Week 6. Each one tells you which tests pass, and has a hint and a solution if you get stuck.

Open Week 6 exercises

Check your understanding

Pick an answer for each question, then press Check answers.

  1. What does d.get("phone", "none") return when "phone" is not a key?
  2. What does looping directly over a dictionary (for x in d) give?
  3. What is {1, 2, 3} & {2, 3, 4}?
  4. Which is an empty set?
  5. Which is NOT allowed as a dictionary key?

This course is for learning. The Python engine runs in your browser and your code is never sent to us.