Python Dictionary Exercise Solution

This solution follows the exercise on dictionary data from CSV-style rows. It keeps the original exercise approach of working without the csv module, while using context managers so files are closed automatically.

Exercise goals
  1. Create student.csv with student name, Physics, Chemistry, Math and attendance data.
  2. Read the file and build a dictionary using the first column as the key.
  3. Display the record for student ID 2.
  4. Create student1.csv from the dictionary.
  5. Create student2.csv after reducing the Physics mark by 2.

Sample student.csv data

1,Ravi,20,30,40,120
2,Raju,30,40,50,130
3,Alex,40,50,60,140
4,Ronn,50,60,70,150

1. Create student.csv from user input

with open('student.csv', 'w', encoding='utf-8') as file:
    for student_id in range(1, 5):
        name = input('Student name: ')
        physics = input('Physics marks: ')
        chemistry = input('Chemistry marks: ')
        math = input('Math marks: ')
        attendance = input('Days present: ')
        row = f'{student_id},{name},{physics},{chemistry},{math},{attendance}\n'
        file.write(row)

Opening the file in w mode makes repeated practice runs predictable instead of appending duplicate records.

2. Read the file and create a dictionary

students = {}

with open('student.csv', 'r', encoding='utf-8') as file:
    for record in file:
        parts = record.rstrip('\n').split(',')
        student_id = parts[0]
        students[student_id] = parts[1:]

print(students)
print(students['2'])

The value stored for each ID is a list in this order: name, Physics, Chemistry, Math and attendance. The rstrip() call removes the line break before splitting the row.

3. Create student1.csv from the dictionary

with open('student1.csv', 'w', encoding='utf-8') as file:
    for student_id, details in students.items():
        row = ','.join([student_id, *details]) + '\n'
        file.write(row)

4. Create student2.csv after reducing Physics by 2

with open('student2.csv', 'w', encoding='utf-8') as file:
    for student_id, details in students.items():
        name, physics, chemistry, math, attendance = details
        physics = str(int(physics) - 2)
        row = ','.join([student_id, name, physics, chemistry, math, attendance]) + '\n'
        file.write(row)

This corrects the intended exercise operation by changing the Physics field specifically. int() converts the mark for arithmetic and str() converts it back for file output.

Download the original exercise ZIP / notebook




Subscribe to our YouTube Channel here



plus2net.com







Python Video Tutorials
Python SQLite Video Tutorials
Python MySQL Video Tutorials
Python Tkinter Video Tutorials
✖
We use cookies to improve your browsing experience. . Learn more
HTML MySQL PHP JavaScript ASP Photoshop Articles Contact us
© 2000-2026 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer