Bird
0
0

Find the bug in this code:

medium📝 Debug Q7 of 15
Python - Structured Data Files
Find the bug in this code:
import csv
with open('input.csv', 'r') as f:
    reader = csv.DictReader(f)
    for row in reader:
        print(row['Name'])

Assuming the CSV header is name,age (all lowercase).
ANo bug, code runs fine
BFile should be opened in binary mode
CMissing delimiter parameter in DictReader
DKeyError due to case mismatch in dictionary key
Step-by-Step Solution
Solution:
  1. Step 1: Check CSV header and key used in code

    CSV header is 'name' lowercase, but code accesses 'Name' with uppercase N.
  2. Step 2: Understand dictionary key sensitivity

    Dictionary keys are case-sensitive, so 'Name' key does not exist, causing KeyError.
  3. Final Answer:

    KeyError due to case mismatch in dictionary key -> Option D
  4. Quick Check:

    DictReader keys are case-sensitive [OK]
Quick Trick: Match dictionary keys exactly to CSV headers (case-sensitive) [OK]
Common Mistakes:
  • Ignoring case sensitivity of keys
  • Opening file in wrong mode
  • Assuming default delimiter is wrong

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes