7. Dictionaries & Sets#
This chapter introduces two of Python’s most powerful built-in data structures: dictionaries and sets.
Dictionaries map keys to values, giving you fast lookup by name rather than by position. They are the foundation of many elegant algorithms — from counting word frequencies to building indexes and caches.
Sets store unordered collections of unique elements. They support efficient membership testing and the classic mathematical operations — union, intersection, and difference — making them ideal for problems like deduplication and finding common elements.
Topics covered in this chapter:
Data Structure |
Topic |
Description |
|---|---|---|
Dict |
Dictionary basics |
Creating, accessing, and modifying key-value pairs |
Dictionary methods |
|
|
Dictionary comprehensions |
Building dictionaries concisely with a single expression |
|
Counting & histograms |
Using dictionaries to tally occurrences |
|
Set |
Set basics |
Creating sets and understanding unordered uniqueness |
Set operations |
Union ( |
|
Set comprehensions |
Building sets concisely with a single expression |
|
Both |
Choosing the right structure |
When to use a list, dict, or set |