Group Items with Defaultdict

Talk it through out loud with your AI coach.

The problem

  • easy
  • Pro

You need to group a list of orders by customer, so each customer maps to a list of their orders. Explain how you'd do it with a plain dictionary, how defaultdict from the collections module simplifies it, and one surprise defaultdict can cause.

What a strong answer covers

  • The usual way to group values with an ordinary dictionary.
  • What defaultdict does automatically and what you give it to do so.
  • A side effect of defaultdict that can catch people out.
  • How to check for a key without changing the dictionary.

Common mistake: Thinking defaultdict only fills in values when you write to it; reading a missing key with square brackets also adds it.

Knowing this is half of it. Saying it clearly out loud is the part the coach helps you practise.

Practise it out loud