Python: Can I use a dictionary for indexing?

This is my first question on StackOverflow, and I searched so many sites, but could not find what I was looking for (or did not notice). Please do not bother me :)

Also, this is my first programming experience with Fitton, and I'm confused.

I have a TXT file and it has 3 columns inside separated by WhiteSpaces. These columns are DeptID , CourseID , CourseID .

Here is an example of data:

 101 10001 23 102 10002 30 102 10004 5 102 10005 13 105 10006 59 105 10007 77 

So, whenever I call the indexes DeptID and CourseID , the program gives me the number of students studying.

Example: NumberofEnrolled("101","10001") should give the answer 23 .

Should matrices be used instead? Because I have lost. I know what I want, but I do not know what it is called in Fiton.

 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] 
Result

test_dict:

 {'101': '10001', '102': '10005', '105': '10007'} 

This output only accepts the latest data for multiple data. I think I need a type that can contain several pairs inside.

+5
source share
4 answers

You can easily read your data in the dictionary of dictionaries:

 data = {} for line in file: dept, course, num_students = line.split() data.setdefault(dept, {})[course] = int(num_students) 

Now you can find:

 >>> data["101"]["10001"] 23 
+7
source

Others have provided you with several options.

I would suggest that since the pair (deptID, courseID) must be unique, you can use tuples as your key.

 depts = dict() depts[(101,10001)] = 23 depts[(102,10002)] = 30 depts[(102,10004)] = 5 depts[(102,10005)] = 13 depts[(105,10006)] = 59 depts[(105,10007)] = 77 print(depts) #output: {(102, 10002): 30, (101, 10001): 23, (105, 10006): 59, (102, 10005): 13, (105, 10007): 77, (102, 10004): 5} print(depts.keys()) #output: [(102, 10002), (101, 10001), (105, 10006), (102, 10005), (105, 10007), (102, 10004)] #should you ever need to access all the courses associated with an ID you #can use a filter with a lambda or more easily a List Comprehension #to identify that data. But this will be have O(n) time look up as opposed #to a dictionary of dictionaries which would have a O(1) look up for #associated courseID lookups. print([catalogue[1] for catalogue in depts.keys() if catalogue[0] == 102]) #output: [10002, 10005, 10004] for (i,j) in depts.keys() : print (depts[(i,j)]) #output: 30 #output: 23 #output: 59 #output: 13 #output: 77 #output: 5 
+3
source

It will be easy to convert your data into a dictionary.

Open the info.txt file and save it as info.csv. The reason for this is because csv can easily handle spaces or commas and any other delimiters.

 import csv data_dict = {} # you can change the delimiter if its something other than space. with open("C:\\Info.txt", "r") as fobj: data = csv.reader(fobj, delimiter=' ') # reading the rows/lines of the file for row in data: if row[0] in data_dict.keys(): data_dict[row[0]][row[1]] = row[2] else: data_dict[row[0]] = {row[1]: row[2]} def func(dept_id, course_id): # check whether the dept_id exists in your current dictonary if dept_id in data_dict.keys(): # check whether the course_id exists in your current dictonary if course_id in data_dict[dept_id].keys(): return data_dict[dept_id][course_id] else: print ('Invalid course id') else: print ('invalid department id') print func('101', '10001') 
+1
source

If you really want to use both DeptID and CourseID, it seems you need a 2-dimensional lookup table (rather than the real Python built-in thing), where first the search, perhaps DeptID (in the dictionary) will give you the CourseIDs table (dictionary) in combined with the registered number corresponding to this department.

Ineffective, but it also seems to me that all CourseIDs will be unique, and if so, is it possible for you to simply search based on this?

0
source

Source: https://habr.com/ru/post/1268309/


All Articles