This is my first question on StackOverflow and I have searched so many websites but couldn't find what I was looking for (or didn't notice). Please do not discourage me :)
Also, This is my first programming experience with Python and I'm confused.
I have a text file and it has 3 columns inside separated with WhiteSpaces. These columns are DeptID
, CourseID
, NumberofStudentsEnrolled
.
Here is the sample data:
101 10001 23
102 10002 30
102 10004 5
102 10005 13
105 10006 59
105 10007 77
So, whenever I call DeptID
indices and CourseID
indices, the program will give me the number of students enrolled.
Example : NumberofEnrolled("101","10001")
should give 23
as answer.
Should I try matrices instead? Because I'm kind of lost. I know what I want, but I don't know what it is called in Python
.
import numpy
depts = []
courses = []
file = open("C:\\Info.txt", "r")
# SPLIT EVERY LINE INTO 3 PIECES : DeptID , CourseID , Enrolled
for line in file:
depts.append(line.split()[0]) # ADD Depts
courses.append(line.split()[1]) # ADD Courses
# CLOSE THE FILE
file.close()
# I HAVE TRIED NUMPY BUT COULDN'T HANDLE WITH IT.
numpyList = numpy.zeros((57, 57), dtype = numpy.int32)
dept_array = numpy.array(dept)
course_array = numpy.array(course)
test_dict = {}
for i in range(len(dept_array)):
test_dict[dept_array[i]] = course_array[i]
test_dict output is:
{'101': '10001', '102': '10005', '105': '10007'}
This output takes only last data for multiple data. I guess I need a type that can hold multiple pairs inside.
You can easily read your data into a dictionary of dictionaries:
data = {}
for line in file:
dept, course, num_students = line.split()
data.setdefault(dept, {})[course] = int(num_students)
Now you can lookup:
>>> data["101"]["10001"]
23
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With