Dictionaries and sets: lookup and uniqueness
Chapter 20 of 132 · Level 1 · Beginner Python textbook · 7 real coding demonstrations + 2 worked code answers. Learn through reading, predicting and testing real Python code.
Course disclaimer · independent educational content
01 · Start here: simple explanation
Sometimes data is better organized by meaning rather than position.
A dictionary maps keys to values. Instead of asking for the second item, you ask for a meaningful key such as "email" or "price". Keys are unique within a dictionary.
To avoid errors when a key may be missing, the get method can supply a default. The items method lets you loop through every key-value pair.
A set stores unique values. It is useful for questions such as “Have we seen this ID before?” or “How many distinct categories exist?” Do not rely on a set for display order.
Dictionaries and sets share curly-brace syntax, but an empty pair of braces creates an empty dictionary. To make an empty set, use set().
02 · Learning objectives and technical words
By the end you can…
- Store related details in a dictionary
- Access and update entries safely
- Use sets to remove duplicate values
Words you should know
- dictionary
- a mapping of keys to values
- key
- a unique lookup identifier in a dictionary
- set
- an unordered collection of unique values
- membership
- a test of whether a value is present
03 · Point-by-point: understand the idea
Locate the input, identify the Python instruction that changes it, and compare the printed result. Make a prediction before each run so you understand what the program does—not only how to copy it.
A dict value is reached by its key, not its numeric position. person[0] is not equivalent to person["name"].
04 · Coding examples with real outputs
Example 1: Describe a person
Python · runnableperson = {"name": "Ava", "age": 24}
print(person["name"])
print(person["age"])
Ava 24
Why it works: A dictionary uses names of fields as keys.
Example 2: Add or update a field
Python · runnablebook = {"title": "Learning Python"}
book["pages"] = 180
print(book["pages"])
180
Why it works: Assignment to a new key adds an entry.
Example 3: Handle a missing key
Python · runnableprofile = {"name": "Ali"}
print(profile.get("city", "Not provided"))
Not provided
Why it works: get returns a default instead of raising KeyError.
Example 4: Loop through dictionary entries
Python · runnableprices = {"pen": 2, "book": 7}
for item, price in prices.items():
print(item, price)
pen 2 book 7
Why it works: items gives each key paired with its value.
Example 5: Make distinct categories
Python · runnablecategories = ["food", "books", "food", "tools"]
unique = set(categories)
print(len(unique))
print("food" in unique)
3 True
Why it works: The count of unique categories is 3 regardless of iteration order.
Example 6: Membership in a dictionary
Python · runnablegrades = {"Lia": 90, "Noah": 84}
print("Lia" in grades)
print("Maya" in grades)
True False
Why it works: in checks dictionary keys, not values.
Example 7: Count repeated words
Python · runnablewords = ["red", "blue", "red"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts["red"])
2
Why it works: get(word, 0) starts a new counter at zero if the word has not been seen.
05 · Exercises, debugging and worked answers
Try without looking
- Create a dictionary with an item and its price, then print the price.
- Count how many unique numbers appear in [2, 2, 3, 4, 4].
- Use get to return "unknown" when a city key is absent.
Worked answers
Worked solution 1: Worked answer: price lookup
Python · runnableitem = {"name": "Pencil", "price": 1.5}
print(item["price"])
1.5
Why it works: The key identifies which value to retrieve.
Worked solution 2: Worked answer: unique values
Python · runnablenumbers = [2, 2, 3, 4, 4]
print(len(set(numbers)))
3
Why it works: Converting to a set removes repeated values.
06 · Build a mini-project and review
Mini-build: A contact book that stores at least three names and phone placeholders, and supports checking whether a name exists.
Can you explain the output before running the code? Can you change the inputs without breaking the program? Revisit the examples until you can do both.
