Sets and Dictionaries
Use sets for unique values and dictionaries for named values.
Sets keep unique values
A set stores unique values. Create one with braces or set(). Sets do not keep a useful item order, so sort them before printing examples.
colors = {'red', 'blue', 'red'}
colors.add('green')
colors.remove('blue')
print(sorted(colors))
The repeated 'red' is kept only once. add() adds a value. remove() removes a value and raises an error if it is missing.
Set operations
a = {1, 2, 3}
b = {3, 4}
print(sorted(a | b))
print(sorted(a & b))
print(sorted(a - b))
| Operation | Meaning | Example |
|---|---|---|
| a | b | Union: values in either set | {1, 2} | {2, 3} |
| a & b | Intersection: shared values | {1, 2} & {2, 3} |
| a - b | Difference: values only in a | {1, 2} - {2, 3} |
Dictionaries connect keys to values
A dictionary maps a unique key to a value. Use square brackets when a key must exist. Use get() when a missing key should return a fallback instead of an error.
student = {'name': 'Ivy', 'score': 8}
print(student['name'])
print(student.get('level', 'beginner'))
student['score'] = 10
student['city'] = 'Lima'
del student['city']
print(student)
Assigning to a new key adds it. Assigning to an existing key updates it. del removes a key and its value.
student = {'name': 'Ivy', 'score': 10}
print(list(student.keys()))
print(list(student.values()))
for key, value in student.items():
print(key + ':', value)
profile = {'user': {'name': 'Ivy', 'active': True}}
print(profile['user']['name'])
Key points
- Sets keep each value only once.
- Sort a set before printing it when order matters.
- Set operators compare groups of values.
- Dictionaries map keys to values.
- get() can safely handle a missing dictionary key.
Worked example
A libary app records who entered today; duplicates collapse in a set. Marks live in a dictionary keyed by student.
visitors = ["Mim", "Rafi", "Mim"]
unique = set(visitors)
marks = {"Mim": 78, "Rafi": 64}
print(len(unique), marks["Mim"])
How it works, step by step
- set() keeps one copy of each value.
- Dictionary lookup uses the KEY in square brackets.
- len(set) counts distinct visitors: 2.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetCreate fruit = {'apple': 3, 'pear': 2}. Add 'banana' with value 5, then print fruit['banana'].
Expected output: 5
# Write your code below
Check yourself
Sets and Dictionaries quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.