CodeBlanks Logo Icon CodeBlanks

Summary - Tuple, set and dict

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

main.py
# Even squares with a dict comprehension

Sample solution

main.py
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

main.py
# Convert a tuple to a set

Sample solution

main.py
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

Question
x, y = (____, 4)
Answer
x, y = (3, 4)

Explanation: The (3, 4) tuple is unpacked as x=3, y=4.

All lessons in Beginner