Bird
Raised Fist0

You have a list of dictionaries:

hard🚀 Application Q8 of Q15
Python - Structured Data Files
You have a list of dictionaries:
data = [
  {'name': 'John', 'age': 28},
  {'name': 'Jane', 'age': 32}
]

Which code correctly writes this data to a CSV file with headers name and age?
Aimport csv with open('people.csv', 'w', newline='') as f: writer = csv.writer(f) writer.writeheader() writer.writerows(data)
Bimport csv with open('people.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=['name', 'age']) writer.writeheader() writer.writerows(data)
Cimport csv with open('people.csv', 'w', newline='') as f: writer = csv.DictReader(f, fieldnames=['name', 'age']) writer.writeheader() writer.writerows(data)
Dimport csv with open('people.csv', 'w') as f: writer = csv.writer(f) writer.writerow(['name', 'age']) writer.writerows(data)
Step-by-Step Solution
Solution:
  1. Step 1: Use csv.DictWriter for list of dictionaries

    csv.DictWriter writes dictionaries to CSV using specified fieldnames and supports writing headers.
  2. Step 2: Validate code correctness

    import csv with open('people.csv', 'w', newline='') as f: writer = csv.DictWriter(f, fieldnames=['name', 'age']) writer.writeheader() writer.writerows(data) correctly opens file with newline='', creates DictWriter with fieldnames, writes header, then writes rows.
  3. Final Answer:

    Use csv.DictWriter with writeheader() and writerows() -> Option B
  4. Quick Check:

    DictWriter writes dicts with headers [OK]
Quick Trick: Use csv.DictWriter for writing dicts with headers [OK]
Common Mistakes:
MISTAKES
  • Using csv.writer for dictionaries directly
  • Confusing DictReader with DictWriter
  • Omitting newline='' causing blank lines

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes