Chapter 8 of 12
Dictionaries are the workhorses of Python โ key-value stores used for everything from function return values to JSON data to caching. Sets are unordered collections of unique values, perfect for membership testing and removing duplicates.
# Creating dictionaries
user = {
"name": "Nelson Njihia",
"age": 26,
"role": "engineer",
"skills": ["Python", "JavaScript", "SQL"],
}
# Accessing values
user["name"] # "Nelson Njihia"
user.get("email") # None (safe โ no KeyError)
user.get("email", "") # "" (default value)
# Modifying
user["email"] = "nelson@nelsonlabs.dev" # add or update
del user["age"] # delete key
# Iterating
for key in user: # keys
print(key)
for value in user.values(): # values
print(value)
for key, value in user.items(): # key-value pairs
print(f"{key}: {value}")
# Dictionary comprehension
squares = {n: n ** 2 for n in range(1, 6)}
# {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Merging dictionaries (Python 3.9+)
defaults = {"theme": "dark", "lang": "en"}
settings = {**defaults, "lang": "sw", "font_size": 16}
# or: settings = defaults | {"lang": "sw"}# Creating sets
tags = {"python", "django", "web"}
numbers = {1, 2, 3, 4, 5}
# Sets ignore duplicates
unique = {1, 2, 2, 3, 3, 3} # {1, 2, 3}
# From a list โ removes duplicates
courses = ["Python", "Python", "Django", "Flask"]
unique_courses = set(courses) # {"Python", "Django", "Flask"}
# Membership โ O(1) time (instant regardless of size)
"python" in tags # True
"rust" in tags # False
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
a | b # {1, 2, 3, 4, 5, 6} โ union (all elements)
a & b # {3, 4} โ intersection (shared)
a - b # {1, 2} โ difference (in a, not in b)
a ^ b # {1, 2, 5, 6} โ symmetric difference
# Modifying
tags.add("flask")
tags.discard("web") # remove if present (no error if missing)