Dictionaries and sets
Use keys for meaningful lookup and sets for membership, uniqueness, and overlap.
By the end, you’ll be able to…
- Read and update dictionary values using descriptive keys.
- Choose between direct lookup and get for missing keys.
- Use set operations and sort results for predictable display.
01Lookup by meaning instead of position
A dictionary associates keys with values. When a learner record contains a name, a city, and a score, looking up record['city'] communicates more than remembering that the city is item 1. Curly braces contain key-value pairs separated by colons. Keys are unique within a dictionary; assigning a value to an existing key replaces the value stored for that key.
Dictionary keys must be hashable. Strings, integers, and tuples of hashable values are common choices; mutable lists are unsuitable. Dictionary values can be arbitrary objects, including lists and other dictionaries. Choose keys that identify the information consistently. If you use 'score' in one place and 'Score' in another, Python treats them as different keys, just as variable names are case-sensitive.
02Decide what a missing key means
Direct access with square brackets raises KeyError when the key is absent. That behavior can be useful when the information is required: it exposes an incorrect assumption. The get method instead returns a default for an absent key, with None as the default if you provide none. get does not insert the default into the dictionary.
Use the in operator to test whether a key exists; it does not search the values. A stored None value and an absent key can look identical when using get without a separate presence check. Decide whether your application needs that distinction. Dictionaries preserve insertion order, but that order is not an automatic sort. Updating an existing key keeps its position, so sort explicitly when a sorted report is required.
03Sets keep distinct members
A set stores unique hashable elements. Use it when the central question is membership or uniqueness rather than position. Repeating a value during construction does not create another copy of that member. A set does not support numeric indexing and does not promise a display order. Sorting a set creates a predictable list for presentation, while leaving the set useful for membership checks.
Curly braces with values create a set, but empty braces create an empty dictionary. Use set() for an empty set. add includes one member and discard removes it if present without complaining if it is absent. Turning a list into a set intentionally loses duplicate counts and positional order. Keep the original list when either of those facts is part of the information you need.
04Compare groups with set operations
Set operations express relationships between groups. Union with | includes members from either group. Intersection with & includes shared members. Difference with - includes members from the left group that are absent from the right. Difference is directional: attendees - paid and paid - attendees answer different questions. Read the names aloud before selecting an operator.
A useful design question is what information identifies each item. A dictionary maps an identifier to associated details; a set only records whether that identifier belongs. For an event, a dictionary might store each attendee's ticket type, while a set stores the identifiers checked in. Choosing a container around the question you want to answer keeps the rest of the code simpler.
The ideas worth keeping.
- Dictionaries connect unique keys to associated values.
- Direct lookup requires a key; get can provide a default without inserting it.
- Sets express membership and group relationships; sort them when displaying ordered results.
Make it yours.
Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.
Optional inventory lookup
Create stock with notebook: 12 and pen: 30. Replace the notebook quantity with 10. Print that quantity and print 0 for the absent eraser key without adding eraser to stock.
Explore a worked solution
stock = {"notebook": 12, "pen": 30}stock["notebook"] = 10print(stock["notebook"])print(stock.get("eraser", 0))print("eraser" in stock)Direct lookup reads the known key; get supplies a fallback for the optional key. The final False confirms that providing a default does not insert a dictionary entry.
Find the learners who need follow-up
Given enrolled = {'Ada', 'Mira', 'Noor'} and submitted = {'Mira', 'Sam'}, print a sorted list of enrolled learners who have not submitted, then a sorted list of submitters who were not enrolled.
Explore a worked solution
enrolled = {"Ada", "Mira", "Noor"}submitted = {"Mira", "Sam"}print(sorted(enrolled - submitted))print(sorted(submitted - enrolled))The outputs are ['Ada', 'Noor'] and ['Sam']. Reversing difference changes the question, while sorting keeps the report deterministic.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
Optional inventory lookup
Create stock with notebook: 12 and pen: 30. Replace the notebook quantity with 10. Print that quantity and print 0 for the absent eraser key without adding eraser to stock.
stock["notebook"]
stock.get("eraser" 0)
"eraser" in stockKeep exploring.
The official references behind this chapter, when you want a second angle or the full details.
One chapter closer.
Reading is a start. Trying it yourself makes the connection.