Lesson 2.2

Dictionaries and sets

Checking membership in a list walks it from the start; checking membership in a set or a dict is effectively constant time.

8mBeginner24k students

Overview

Stop scanning lists

Checking membership in a list walks it from the start; checking membership in a set or a dict is effectively constant time. Converting a lookup list to a set is often the entire fix for a script that got slow as its input grew.

Dictionaries preserve insertion order and are the natural shape for records keyed by id. Grouping is the most common operation you will write, and a default dictionary removes the does-this-key-exist boilerplate.

Set algebra — union, intersection, difference — answers which-items-are-in-both questions directly, without any loop at all.

In this lesson you will:

  • Look up by key instead of scanning a list
  • Use a set for membership and deduplication
  • Group records with a default dictionary

Resources

Previous Lesson
Next Lesson
Dictionaries and sets — Python Foundations for Data Work — Vertex