Python : Can Dictionary be used for indexing?

Viewed 115

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.

4 Answers
Related