Skip to content
Python for Quantitative Finance / Built-In Data Structures

Dictionaries and Sets

Every sequence type this topic has covered so far — str, tuple, range, list — is indexed by position: element 0, element 1, and so on. Many real problems, though, need lookup by label, not position: a ticker symbol mapping to a company name, a currency pair mapping to an exchange rate, a date mapping to a closing price. Dictionaries provide exactly this: a mutable collection of key/value pairs, with fast lookup by key. Sets, this topic's closing structure, are the special case of "just the keys, no values attached" — a collection whose only question is membership. Together, dictionaries and sets are the natural representation, named directly in docs/programme-profiles/library/introduction-to-python.md's Stage 4, for labelled financial series and parameter maps.
Learning objectives. By the end of this note you should be able to:
  • construct, index, and mutate a dictionary, and correctly iterate over its keys, values, or key/value pairs;
  • explain the hashability requirement for dictionary keys, and state why tuples (but not lists) can serve as keys;
  • construct a set, test membership, and compute unions, intersections, and differences using both operator and method syntax;
  • choose correctly among dict, set, list, and tuple for a given labelled- or membership-based data problem.

In this lesson

  1. Dictionaries: key/value pairs
  2. Iterating over a dictionary
  3. Hashability: why tuples, not lists, can be dictionary keys
  4. Sets: membership without values
  5. Choosing among the four structures

Before you start

The full lesson, with worked examples and exercise solutions, is for members.

Read the full lesson

New to SelfMadeQuant.com? See membership options or browse the Python for Quantitative Finance syllabus.