PCEP-30-02 · Question #54
Insert the correct snippet to convert the t tuple to a dictionary named d. Expected output: {'A': 1, 'B': 2, 'C': 3} Code: t = (('A', 1), ('B', 2), ('C', 3)) insert code here print(d)
The correct answer is B. d = dict(t). Option B is correct because Python's built-in dict() function accepts an iterable of key-value pairs - exactly what t is: a tuple of 2-element tuples. Each inner tuple ('A', 1) becomes a key-value pair in the resulting dictionary. Why the distractors fail: A (t >> d.dict) - >>…
Question
insert code here
print(d)Options
- At >> d.dict
- Bd = dict(t)
- Cd.dict(t)
- Dd = t(dict)
How the community answered
(20 responses)- A5% (1)
- B80% (16)
- C10% (2)
- D5% (1)
Explanation
Option B is correct because Python's built-in dict() function accepts an iterable of key-value pairs - exactly what t is: a tuple of 2-element tuples. Each inner tuple ('A', 1) becomes a key-value pair in the resulting dictionary.
Why the distractors fail:
- A (
t >> d.dict) ->>is a bitwise right-shift operator, not a conversion method, andddoesn't exist yet sod.dictwould raise aNameError. - C (
d.dict(t)) -dhasn't been defined, and even if it had, dictionaries have no.dict()method; this would raiseAttributeError. - D (
d = t(dict)) - this tries to call the tupletlike a function withdictas an argument, which raisesTypeErrorsince tuples aren't callable.
Memory tip: Think of dict() as a factory that "zips up" pairs into a dictionary - if your data is already shaped as (key, value) pairs, dict() handles the conversion directly, just like list() or tuple() convert other iterables.
Community Discussion
No community discussion yet for this question.