Bird
0
0

What will be the output of this code snippet?

medium📝 Predict Output Q4 of 15
Python - Structured Data Files
What will be the output of this code snippet?
import csv
from io import StringIO

csv_content = 'name,age\nAlice,30\nBob,25'
file = StringIO(csv_content)
reader = csv.DictReader(file)
for row in reader:
    print(row['age'])
AAlice\nBob
B30\n25
Cname\nage
DError: KeyError
Step-by-Step Solution
Solution:
  1. Step 1: Understand the CSV content and DictReader usage

    The CSV has headers 'name' and 'age', with two rows: Alice 30, Bob 25.
  2. Step 2: Loop prints the 'age' value from each row dictionary

    It prints '30' then '25' on separate lines.
  3. Final Answer:

    30\n25 -> Option B
  4. Quick Check:

    DictReader row['age'] prints ages 30 and 25 [OK]
Quick Trick: DictReader keys are headers; access values by column name [OK]
Common Mistakes:
  • Printing keys instead of values
  • Expecting names instead of ages
  • Confusing header row as data

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes