Bird
0
0

You have a CSV file with columns 'Name', 'Age', and 'City'. You want to read it and create a dictionary where keys are names and values are ages (as integers). Which code snippet correctly does this?

hard📝 Application Q15 of 15
Python - Structured Data Files
You have a CSV file with columns 'Name', 'Age', and 'City'. You want to read it and create a dictionary where keys are names and values are ages (as integers). Which code snippet correctly does this?
Aimport csv with open('data.csv', 'r') as f: reader = csv.DictReader(f) result = {row['Name']: int(row['Age']) for row in reader} print(result)
Bimport csv with open('data.csv', 'r') as f: reader = csv.reader(f) result = {row[0]: int(row[1]) for row in reader} print(result)
Cimport csv with open('data.csv', 'r') as f: reader = csv.DictReader(f) result = {row['Age']: row['Name'] for row in reader} print(result)
Dimport csv with open('data.csv', 'r') as f: reader = csv.reader(f) result = {int(row[1]): row[0] for row in reader} print(result)
Step-by-Step Solution
Solution:
  1. Step 1: Use csv.DictReader to access columns by name

    DictReader reads rows as dictionaries, so we can use keys like 'Name' and 'Age'.
  2. Step 2: Create dictionary with names as keys and ages as integer values

    The comprehension uses row['Name'] as key and converts row['Age'] to int for value.
  3. Final Answer:

    import csv with open('data.csv', 'r') as f: reader = csv.DictReader(f) result = {row['Name']: int(row['Age']) for row in reader} print(result) -> Option A
  4. Quick Check:

    DictReader + dict comprehension with int conversion [OK]
Quick Trick: Use DictReader and convert age to int in comprehension [OK]
Common Mistakes:
  • Using csv.reader without column names
  • Swapping keys and values
  • Not converting age to int

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes