PCEP-30-02 · Question #59
What is the expected output of the following code? data = {} data[1] = 1 data['1'] = 2 data[1.0] = 4 res = 0 for d in data: res += data[d] print(res)
The correct answer is C. 6. Option C (6) is correct because Python considers integer 1 and float 1.0 as equal keys in a dictionary - they have the same hash value and compare equal (1 == 1.0 is True), so data[1.0] = 4 overwrites data[1] = 1. The final dictionary holds only two entries: key 1 (value 4) and…
Question
Options
- A3
- BThe code is erroneous.
- C6
- D7
How the community answered
(19 responses)- A11% (2)
- B5% (1)
- C79% (15)
- D5% (1)
Explanation
Option C (6) is correct because Python considers integer 1 and float 1.0 as equal keys in a dictionary - they have the same hash value and compare equal (1 == 1.0 is True), so data[1.0] = 4 overwrites data[1] = 1. The final dictionary holds only two entries: key 1 (value 4) and key '1' (value 2), giving res = 4 + 2 = 6.
Why the distractors fail:
- D (7) is the most tempting trap - it assumes all three assignments create separate keys (
1 + 2 + 4), but1and1.0collapse into one. - A (3) might arise from thinking
1.0overwrites both integer entries and only'1'and one numeric key remain as1 + 2, but that's not how it works either. - B (erroneous) is wrong because Python handles mixed numeric key types gracefully - no error is raised.
Memory tip: Remember "same hash, same key" - Python's dict uses hash equality, and integers/floats with the same numeric value always share a hash, so 1, 1.0, and even True are all the same dictionary key.
Community Discussion
No community discussion yet for this question.