# Solution to Dictionary Exercise in Python

1. Create a file student.csv by taking data for 5 students in three subjects and attendance data of the year. Inputs are student name, mark in Physics, Chemistry, Math and Attendance. After entering all data your file should look like this.
``````1,Ravi,20,30,40,120
2,Raju,30,40,50,130
3,Alex,40,50,60,140
4,Ronn,50,60,70,150``````
2. After creating the student.csv file, read the data from this file and create a dictionary using this data. Use key as first column serial numbers and rest of the data ( name , mark in three subjects and attendance ) as a list.
3. Print one sample record of student id 2
4. Using the above created dictionary crate one more csv file student1.csv using the same data.
5. Create one more csv file student2.csv file by using the same dictionary after reducing mark in Physics by 2 for all students.
We are not importing CSV module for the solution.

## Solution

``````#create a dictionary with student name and marks.
#Use student name as key
#User has to enter all data.

fob=open('student.csv','a')
data=''
for i in range(1,5):
n=input("Student Name : ")
a=input("\n Enter maths marks: ")
b=input("Enter physics marks: ")
c=input("Enter Chemistry marks: ")
p=input("Enter no of days present: ")
data=str(i)+','+n+','+a+','+b+','+c+','+p+'\n'
fob.write(data)
fob.close()``````
creating dictionary and showing data
``````fob=open('student.csv','r')
my_dict={}
for rec in fob:
n=rec.split(',')
print(n)
my_dict.update({n:[n,n,n,n,n[-1].rstrip('\n')]})
fob.close()
print(my_dict)
print(my_dict['2'])
print(my_dict['2'])``````
Read student details from a CSV file and prepare a dictionary
Used string method rstrip() to remove the line break ( \n ) from the last element of the list.
``````fob=open('student.csv','r')
my_dict={}
for rec in fob:
n=rec.split(',')
print(n)
my_dict.update({n:[n,n,n,n,n[-1].rstrip('\n')]})
fob.close()
print(my_dict)
print(my_dict['2'])
print(my_dict['2'])``````
Create one file student1.csv using dictionary data. We used append mode for file write.
``````fob=open('student1.csv','a')
data=''
for i in my_dict:
data=i +','+ my_dict[i] +','+ my_dict[i] +',' +my_dict[i]
data = data + ','+my_dict[i] + ','+ my_dict[i] + '\n'
fob.write(data)
fob.close() ``````
Create one more csv file after reducing mark in Physics. We used int() to convert string to integer and then used str() to again convert integer to string after reducing the mark.
``````fob=open('student2.csv','a')
data=''
for i in my_dict:
data=i +','+ my_dict[i] +','+ my_dict[i] +',' +str(int(my_dict[i])-2)
data = data + ','+my_dict[i] + ','+ my_dict[i] + '\n'
fob.write(data)
fob.close() ``````

Subscribe to our YouTube Channel here

## Subscribe

* indicates required
Subscribe to plus2net plus2net.com