Summary - Tuple, set and dict
- Python course
- Beginner
- Lesson 70/116
- 5 min
Combine tuple, set and dict to write a phone book.
Summary - Tuple, set and dict
In this group we covered tuple, set, dict and their methods.
- Tuple: immutable, parentheses.
- Set: unordered, unique, curly braces.
- Dict: key-value, curly with colon.
- Dict methods: keys, values, items, get, pop, update.
- Dict comprehension: {k: v for ...}.
Now two tasks combine these concepts.
Practice Even squares with a dict comprehension
Assign to even_squares a dict comprehension that holds the squares of even numbers from [1, 2, 3, 4, 5, 6]. Then print print(even_squares).
Starter code
# Even squares with a dict comprehensionSample solution
even_squares = {n: n * n for n in [1, 2, 3, 4, 5, 6] if n % 2 == 0}
print(even_squares)Expected output
{2: 4, 4: 16, 6: 36}
Practice Tuple and set together
Assign the tuple (3, 4) to point. Assign set(point) to coords. Then print print(sorted(coords)).
Starter code
# Convert a tuple to a setSample solution
point = (3, 4)
coords = set(point)
print(sorted(coords))Expected output
[3, 4]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which statement is correct?
- A tuple is mutable
- A set keeps duplicates
- A set is an ordered collection
- Dict keys must be unique Correct answer
Explanation: Tuple is immutable, set is unique and unordered.
2 Unpack a tuple
x, y = (____, 4)
x, y = (3, 4)
Explanation: The (3, 4) tuple is unpacked as x=3, y=4.