Bird
0
0

Given a CSV file with columns product,price,quantity, which code snippet correctly creates a dictionary mapping each product to its total value (price multiplied by quantity) using csv.DictReader?

hard📝 Application Q8 of 15
Python - Structured Data Files
Given a CSV file with columns product,price,quantity, which code snippet correctly creates a dictionary mapping each product to its total value (price multiplied by quantity) using csv.DictReader?
Aimport csv with open('products.csv') as f: reader = csv.reader(f) totals = {row[0]: row[1] * row[2] for row in reader}
Bimport csv with open('products.csv') as f: reader = csv.DictReader(f) totals = {row['product']: float(row['price']) * int(row['quantity']) for row in reader}
Cimport csv with open('products.csv') as f: reader = csv.DictReader(f) totals = {row['product']: row['price'] + row['quantity'] for row in reader}
Dimport csv with open('products.csv') as f: reader = csv.DictReader(f) totals = {row['product']: int(row['price']) * int(row['quantity']) for row in reader}
Step-by-Step Solution
Solution:
  1. Step 1: Use csv.DictReader to read rows as dicts

    This allows accessing columns by name.
  2. Step 2: Convert price and quantity to numeric types

    Price may be float, quantity integer; convert accordingly before multiplication.
  3. Step 3: Create dictionary comprehension mapping product to total value

    Multiply converted price and quantity for each row.
  4. Final Answer:

    import csv with open('products.csv') as f: reader = csv.DictReader(f) totals = {row['product']: float(row['price']) * int(row['quantity']) for row in reader} correctly implements these steps.
  5. Quick Check:

    Convert strings to numbers before multiplying [OK]
Quick Trick: Convert strings to numbers before math operations [OK]
Common Mistakes:
  • Using csv.reader instead of DictReader
  • Not converting strings to numeric types before multiplication
  • Adding price and quantity instead of multiplying

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes