Bird
0
0

Which code snippet correctly does this?

hard📝 Application Q15 of 15
Python - Structured Data Files
You have a CSV file with columns 'id', 'name', and 'score'. You want to read it using csv.DictReader and create a dictionary mapping each 'id' to the 'score' as an integer. Which code snippet correctly does this?
Awith open('data.csv') as f: reader = csv.DictReader(f) result = {int(row['id']): row['score'] for row in reader}
Bwith open('data.csv') as f: reader = csv.DictReader(f) result = {row['id']: int(row['score']) for row in reader}
Cwith open('data.csv') as f: reader = csv.reader(f) result = {row['id']: int(row['score']) for row in reader}
Dwith open('data.csv') as f: reader = csv.DictReader(f) result = {row['score']: int(row['id']) for row in reader}
Step-by-Step Solution
Solution:
  1. Step 1: Use DictReader to access columns by name

    Only csv.DictReader allows accessing 'id' and 'score' by keys.
  2. Step 2: Create dictionary with 'id' as key and integer 'score' as value

    with open('data.csv') as f: reader = csv.DictReader(f) result = {row['id']: int(row['score']) for row in reader} correctly converts 'score' to int and uses 'id' as key.
  3. Final Answer:

    with open('data.csv') as f: reader = csv.DictReader(f) result = {row['id']: int(row['score']) for row in reader} -> Option B
  4. Quick Check:

    DictReader + dict comprehension + int conversion [OK]
Quick Trick: Use DictReader and dict comprehension with int() conversion [OK]
Common Mistakes:
  • Using csv.reader instead of DictReader
  • Swapping keys and values in dictionary
  • Not converting score to int
  • Converting id to int instead of score

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More Python Quizzes