Complete the code to open a CSV file for reading using a dictionary reader.
import csv with open('data.csv', [1]) as file: reader = csv.DictReader(file) for row in reader: print(row)
To read a CSV file, you open it in read mode using 'r'.
Complete the code to write a list of dictionaries to a CSV file using DictWriter.
import csv fieldnames = ['name', 'age'] data = [{'name': 'Alice', 'age': 30}, {'name': 'Bob', 'age': 25}] with open('output.csv', 'w', newline='') as file: writer = csv.DictWriter(file, fieldnames=[1]) writer.writeheader() writer.writerows(data)
The fieldnames parameter tells DictWriter the order and names of columns.
Fix the error in the code to correctly read and print the 'age' from each row in the CSV.
import csv with open('people.csv', 'r') as file: reader = csv.DictReader(file) for row in reader: print(row[[1]])
row['age'] inside the brackets.To access the 'age' value in each row dictionary, use the key as a string: 'age'.
Fill both blanks to create a dictionary comprehension that maps names to ages from a list of rows.
rows = [{'name': 'Anna', 'age': '22'}, {'name': 'Ben', 'age': '28'}]
name_age = { [1]: [2] for row in rows }The dictionary comprehension uses row['name'] as key and row['age'] as value.
Fill all three blanks to filter rows where age is greater than 25 and create a dictionary of name to age.
rows = [{'name': 'Cara', 'age': 24}, {'name': 'Dave', 'age': 30}, {'name': 'Eve', 'age': 27}]
filtered = { [1]: [2] for row in rows if row[[3]] > 25 }The comprehension uses row['name'] as key, row['age'] as value, and filters where row['age'] > 25.