CHAPTER 07 · BEGINNER4 min read

Dictionaries and sets

Use keys for meaningful lookup and sets for membership, uniqueness, and overlap.

Python 3.12+Free to readModule 2 of 13
YOUR NEXT SMALL WINS

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.

learner_record.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

optional_fields.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

unique_topics.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

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.

compare_groups.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
LET IT CLICK

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.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

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.

01

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.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
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.

02

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.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
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.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01What does 'Ada' in {'name': 'Ada'} test?
02What does {} create?
03Which operation finds required skills that are missing from existing_skills?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

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.

EXPECTED OUTPUT
stock["notebook"]
stock.get("eraser" 0)
"eraser" in stock
challenge.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep 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.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock chapter completion.