Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Retrieve data from the list on the basis of value in Python

In a Python program, I’m storing student information in a list, which I want to retrieve on the basis of value (class name).

Let’s say I want to print complete student details. I’ll write this code:

for i in range(len(studentDetails)):
    for j in range(len(studentDetails[i])):
        print(studentDetails[i][j], end=" ")
    print()

Data

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

studentDetail = [studentName, "Class: ", studentClass, "Marks:", studentMarks, "Grade: ", studentGrade]

[Dostoevsky, "Class: ", 1, "Marks: ", 100, "Grade: ", "A+"]
[Tolstoy, "Class: ", 1, "Marks: ", 90, "Grade: ", "A-"]
[Chekhov, "Class: ", 2, "Marks: ", 80, "Grade: ", "A"]
[Kafka, "Class: ", 2, "Marks: ", 75, "Grade: ", "B"]

I now want to print this way from the following data:

Result

Summary
Class 1
Dostoevsky    100    A+
Tolstoy        90    A-
Class 2
Chekhov       80     A
Kafka         75     B

>Solution :

Here is one way to do it:

studentDetails = [["Dostoevsky", "Class: ", 1, "Marks: ", 100, "Grade: ", "A+"],
["Tolstoy", "Class: ", 1, "Marks: ", 90, "Grade: ", "A-"],
["Chekov", "Class: ", 2, "Marks: ", 80, "Grade: ", "A"],
["Kafka", "Class: ", 2, "Marks: ", 75, "Grade: ", "B"]]
studentDetails.sort() #Sort the list by alphabetical order first
studentDetails.sort(key = lambda x: x[2]) #Sort the list by second element(classes)
print("Summary")
curClass = 0 #Current class nummber
for i in studentDetails: #Loops through all the student details
  if curClass != i[2]: #If the currect class number is not equal to the class number that's already printed
    curClass = i[2] #Replace the currect class number
    print("Class", curClass) #Print out the current class number
  print(i[0], i[4], i[6]) #Print out info

This works even when you add more data or class numbers. Hope it helps!

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading