Searching of objects from an array of objects using ID in Python

Here, we are going to learn how to saech of objects from an array of objects using ID in Python?
Submitted by Shivang Yadav, on February 17, 2021

Problem Statement: Program to illustrate searching of objects from an array of objects using ID in Python

Problem Description: We need to create a class to take the students information from the user and the print the object whose id matches the enter input id.

Class Used in the program:

  • Class : student
    • Method : getStudentInfo() : gets input of the student information from the user.
    • Method : putStudentInfo() : print in student information to the screen.
    • For searching, we have the inbuilt method get().

Algorithm:

  • Step 1: Taking input from the user for id, name, marks of the student.
  • Step 2: Print information, of the user using the putStudentInfo() method.
  • Step 3: We took an id to be searched from the user. And then using get() method which will return "Not Found", if no match for the roll number is found in the object.

Program to illustrate the working of our solution

class Student:
    def getStudentInfo(self):
        self.__rollno = input("Enter Roll Number : ")
        self.__name = input("Enter Name : ")
        self.__marks = int(input("Enter Marks : "))
        return self.__rollno
        
    def putStudentInfo(self):
        print(self.__rollno,self.__name,self.__marks)
        
StudentList = {}
while(True):
    studentInfo=Student()
    key = studentInfo.getStudentInfo()
    StudentList.setdefault(key,studentInfo)
    ch=input("Add More y/n?")
    if(ch=='n'):break

print("All Student's Information : ")
L = StudentList.values()
for studentInfo in L:
    studentInfo.putStudentInfo()

roll = input("Enter Roll Number you Want to Search: ")
studentInfo = StudentList.get(roll,"Not Found....")
if isinstance(studentInfo,Student):
    studentInfo.putStudentInfo()

Output:

Enter Roll Number : 1
Enter Name : John
Enter Marks : 87
Add More y/n?y
Enter Roll Number : 4
Enter Name : Joe
Enter Marks : 54
Add More y/n?n
All Student's Information : 
1 John 87
4 Joe 54
Enter Roll Number you Want to Search: 1
1 John 87

Python class & object programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.