0
0
Pythonprogramming~10 mins

Dictionary-based CSV handling in Python - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to open a CSV file for reading using a dictionary reader.

Python
import csv
with open('data.csv', [1]) as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row)
Drag options to blanks, or click blank then click option'
A'x'
B'r'
C'a'
D'w'
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'w' or 'a' mode instead of 'r' causes errors or overwrites the file.
2fill in blank
medium

Complete the code to write a list of dictionaries to a CSV file using DictWriter.

Python
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)
Drag options to blanks, or click blank then click option'
Afieldnames
Bfile
Cwriter
Ddata
Attempts:
3 left
💡 Hint
Common Mistakes
Passing the data list instead of the fieldnames list to DictWriter.
3fill in blank
hard

Fix the error in the code to correctly read and print the 'age' from each row in the CSV.

Python
import csv
with open('people.csv', 'r') as file:
    reader = csv.DictReader(file)
    for row in reader:
        print(row[[1]])
Drag options to blanks, or click blank then click option'
Arow['age']
B'name'
Cage
D'age'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names without quotes as dictionary keys.
Trying to use row['age'] inside the brackets.
4fill in blank
hard

Fill both blanks to create a dictionary comprehension that maps names to ages from a list of rows.

Python
rows = [{'name': 'Anna', 'age': '22'}, {'name': 'Ben', 'age': '28'}]
name_age = { [1]: [2] for row in rows }
Drag options to blanks, or click blank then click option'
Arow['name']
Brow['age']
Attempts:
3 left
💡 Hint
Common Mistakes
Swapping keys and values in the comprehension.
Using the same expression for both key and value.
5fill in blank
hard

Fill all three blanks to filter rows where age is greater than 25 and create a dictionary of name to age.

Python
rows = [{'name': 'Cara', 'age': 24}, {'name': 'Dave', 'age': 30}, {'name': 'Eve', 'age': 27}]
filtered = { [1]: [2] for row in rows if row[[3]] > 25 }
Drag options to blanks, or click blank then click option'
Arow['name']
Brow['age']
C'age'
D'name'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong key in the filter condition.
Swapping keys and values in the dictionary comprehension.