Aller au contenu principal

03.2 - Dictionaries & Sets

Theory 25 min Beginner

Dictionaries

A dictionary (dict) stores key-value pairs. Keys must be unique and hashable (strings, numbers, tuples). Values can be anything.

# Creating dicts
person = {"name": "Alice", "age": 30, "city": "Montreal"}
empty = {}
from_pairs = dict([("a", 1), ("b", 2)])
from_keys = dict.fromkeys(["x", "y", "z"], 0) # {x:0, y:0, z:0}

# Nesting
config = {
"database": {
"host": "localhost",
"port": 5432
},
"debug": True
}
config["database"]["host"] # "localhost"

Accessing Values

person = {"name": "Alice", "age": 30}

# Direct access (KeyError if missing)
person["name"] # "Alice"
person["email"] # KeyError!

# Safe access with .get()
person.get("email") # None (no error)
person.get("email", "N/A") # "N/A" (default)

# Check existence
"name" in person # True
"email" in person # False

Modifying Dictionaries

d = {"a": 1, "b": 2}

# Add/update
d["c"] = 3 # add new key
d["a"] = 10 # update existing

# Update multiple keys
d.update({"b": 20, "d": 4})

# Merge dicts (Python 3.9+)
defaults = {"color": "blue", "size": "M"}
overrides = {"size": "L", "weight": 70}
merged = defaults | overrides # {"color": "blue", "size": "L", "weight": 70}
defaults |= overrides # in-place merge

# Remove
del d["a"] # KeyError if missing
val = d.pop("b") # remove & return value
d.popitem() # remove & return last item (Python 3.7+)
d.clear() # empty the dict

Iterating Over Dicts

person = {"name": "Alice", "age": 30, "city": "Montreal"}

# Keys (default)
for key in person:
print(key)

# Values
for value in person.values():
print(value)

# Key-value pairs (most common)
for key, value in person.items():
print(f"{key}: {value}")

Useful Dict Methods

MethodDescription
d.get(k, default)Safe access with fallback
d.keys()View of all keys
d.values()View of all values
d.items()View of (key, value) pairs
d.update(other)Merge another dict
d.pop(k)Remove and return value
d.setdefault(k, v)Get value or set default if missing
# setdefault — get or initialize
word_count = {}
for word in "the quick brown fox the fox".split():
word_count.setdefault(word, 0)
word_count[word] += 1
# {"the": 2, "quick": 1, "brown": 1, "fox": 2}

# Or with defaultdict (cleaner)
from collections import defaultdict
word_count = defaultdict(int)
for word in text.split():
word_count[word] += 1

Sets

A set is an unordered collection of unique elements. Ideal for membership testing and mathematical set operations.

# Creating sets
fruits = {"apple", "banana", "cherry"}
numbers = {1, 2, 3, 4, 5}
empty = set() # NOT {} (that's an empty dict!)

# From iterable (removes duplicates)
unique = set([1, 2, 2, 3, 3, 4]) # {1, 2, 3, 4}
letters = set("mississippi") # {'m','i','s','p'}

Set Operations

Sets support full mathematical set algebra:

a = {1, 2, 3, 4, 5}
b = {3, 4, 5, 6, 7}

# Union — elements in a OR b
a | b # {1, 2, 3, 4, 5, 6, 7}
a.union(b)

# Intersection — elements in a AND b
a & b # {3, 4, 5}
a.intersection(b)

# Difference — in a but NOT in b
a - b # {1, 2}
a.difference(b)

# Symmetric difference — in a OR b but NOT both
a ^ b # {1, 2, 6, 7}
a.symmetric_difference(b)

# Subset / Superset
{1, 2} <= a # True (subset)
a >= {1, 2} # True (superset)
{1, 2}.issubset(a) # True

Set Methods

s = {1, 2, 3}

s.add(4) # {1, 2, 3, 4}
s.remove(2) # KeyError if missing!
s.discard(10) # No error if missing
s.pop() # Remove and return arbitrary element
len(s) # 3
2 in s # True (O(1) — faster than list!)

Real-World Use Cases

Dict as a switch/lookup table

# Instead of long if/elif chains
operations = {
"add": lambda a, b: a + b,
"subtract": lambda a, b: a - b,
"multiply": lambda a, b: a * b,
"divide": lambda a, b: a / b if b != 0 else None,
}

result = operations.get("add", lambda a, b: None)(10, 5) # 15

Set for fast deduplication and membership

# Remove duplicates preserving order
seen = set()
unique = [x for x in items if not (x in seen or seen.add(x))]

# Find common elements between two lists (fast)
list_a = [1, 2, 3, 4, 5]
list_b = [3, 4, 5, 6, 7]
common = set(list_a) & set(list_b) # {3, 4, 5}

# Membership test: O(1) for set, O(n) for list
valid_commands = {"start", "stop", "restart", "status"}
if command in valid_commands: # instant lookup
execute(command)

Key Vocabulary

TermDefinition
DictionaryKey-value store; keys must be unique and hashable
KeyThe identifier used to access a value in a dict
HashableAn object that can be used as a dict key or set element
SetUnordered collection of unique, hashable elements
Union`a
Intersectiona & b — elements common to both sets
Differencea - b — elements in a but not in b
dict.get()Safe key access with optional default value
setdefault()Returns value for key, inserting default if missing

Summary

  • Dicts {"key": value} store key-value pairs — keys must be unique and hashable
  • Access with d["key"] (raises KeyError) or d.get("key", default) (safe)
  • Iterate with .keys(), .values(), .items() — use .items() for key+value
  • Use | to merge dicts (Python 3.9+) or update() for older versions
  • Sets {1, 2, 3} store unique elements — fast O(1) membership testing
  • Set operations: | (union), & (intersection), - (difference), ^ (symmetric diff)