t l n
t l n

Reputation: 25

how do we grab a specific information like the name from this?

I'm looking at this example and I want to figure out how can I search up a name instead of the ID, then display all the information for the name? For example if it has the ID of 1, name: Bob, department: sales, and job title: manager. If we search up "Bob", everything will display. Sorry this is long.

class Employee:
    def __init__(self, name, ID, department, job_title):
        self.__name = name
        self.__ID = ID
        self.__dept = department
        self.__job = job_title

    def set_name(self, name):
        self.__name = name

    def set_department(self, department):
        self.__dept = department

    def set_job_title(self, job_title):
        self.__job = job_title

    def get_name(self):
        return self.__name

    def get_ID_number(self):
        return self.__ID

    def get_department(self):
        return self.__dept

    def get_job_title(self):
        return self.__job

    def __str__(self):
        return 'Name: ' + self.__name + '\n' + \
               'ID Number: ' + str(self.__ID) + '\n' + \
               'Department: ' + self.__dept + '\n' + \
               'Job Title: ' + self.__job
import pickle

def pickle_it(employees):
    # Open file in binary write mode
    output_file = open('employees.dat', 'wb')
    # Write the data to the file
    pickle.dump(employees, output_file)
    # Close the file
    output_file.close()

def unpickle_it():
    try:
        # Attempt to open file in binary read mode
        input_file = open('employees.dat', 'rb')
    except IOError:
        # If the file doesn't exist, then create it by opening using write
        # mode.  Then just close and reopen in binary read mode.
        file = open('employees.dat', 'wb')
        file.close()
        input_file = open('employees.dat', 'rb')

    # Load the employees dictionary or create an empty dictionary if file is
    # empty
    try:
        employees = pickle.load(input_file)
    except:
        employees = {}

    # Close the file
    input_file.close()

    # Return the employees dictionary
    return employees
import menu_choices
import save_load_dict

# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5

def main():
    employees = save_load_dict.unpickle_it()

    choice = menu_choices.get_menu_choice()

    while choice != QUIT:
        if choice == LOOK_UP:
            menu_choices.look_up(employees)
        elif choice == ADD:
            menu_choices.add(employees)
        elif choice == CHANGE:
            menu_choices.change(employees)
        elif choice == DELETE:
            menu_choices.delete(employees)

        choice = menu_choices.get_menu_choice()

    save_load_dict.pickle_it(employees)

main()
import employee_class

# Global constants for menu choices
LOOK_UP = 1
ADD = 2
CHANGE = 3
DELETE = 4
QUIT = 5

def get_menu_choice():

    print('\n\033[4m' + 'Employee Directory' + '\033[0m')
    print('1. Look up an employee')
    print('2. Add a new employee')
    print('3. Edit an employee\'s information')
    print('4. Delete an employee')
    print('5. Quit\n')

    # Get the user's choice.
    choice = int(input('Enter your choice: '))

    # Validate the choice.
    while choice < LOOK_UP or choice > QUIT:
        choice = int(input('Enter a valid choice: '))

    # return the user's choice.
    return choice

# The look_up function looks up an employee and displays their information.
def look_up(employees):
    # Get a name to look up.
    ID = input('Enter an employee ID number: ')

    # Look it up in the dictionary.
    if ID in employees:
        print(employees[ID])
    else:
        print('That ID number is not found.')

# The add function adds a new entry into the dictionary.
def add(employees):
    # Get employee information.
    name = input('Enter the employee\'s name: ')
    ID = input('Enter the employee\'s ID number: ')
    department = input('Enter the employee\'s department: ')
    job_title = input('Enter the employee\'s job title: ')

    # If the name does not exist, add it.
    if ID not in employees:
        employees[ID] = employee_class.Employee(name, ID, department, \
                                                job_title)
    else:
        print('An entry with that ID number already exists.')

Upvotes: 0

Views: 287

Answers (2)

SimonR
SimonR

Reputation: 1824

You'll need to take into account that two employees could have the same name. The following code (adapted from your existing look_up function) will return all the employees with the name specified, or a message that there are no employees with that name :

# The look_up function looks up an employee by name and displays their information.
def look_up_by_name(employees):
    # Get a name to look up.
    name = input('Enter an employee Name: ')

    matches = [emp for emp in employees if emp['name'] == name]

    if len(matches) == 0:
        print('No employees with name "{}" found'.format(name))
    else:
        for m in matches:
            print(m)

Upvotes: 1

dumbPy
dumbPy

Reputation: 1518

  1. Your question heading asks for how to search using email while the class Employee has no email attribute.
  2. To search using other attribute like Name:

    Though the code snippets you pasted doesn't define what employees object is, it's a dict mapping between id and corresponding Employee object.
    If you only need to search by name, you can make the employees dictionary as a mapping between Name and Employee objects (list, as multiple employee can have same name).

    If you need a more dynamic solution that lets you search by just about anything, then you need to match with all attributes of each Employee object. And also will need to take care of case insensitivity in search.

def look_up(employees):
    # Get any searchtext to lookup
    searchtext = input('Enter search query to lookup')
    matches = [emp for emp in employees.values()
               if searchtext.lower() in [
                   emp.get_name().lower(),
                   emp.get_ID_number(),        # Add .lower() if needed 
                   emp.get_department().lower(), #.lower() for case insensitive match
                   emp.get_job_title().lower()
                ]
               ]
    if not matches:
        print(f'No employee matches any attribute for searchtext {searchtext}')
        return None
    # If there are valid matches
    print(matches)

Eliminate any of the above fields if not needed.

You can go more crazier in terms of matching the string with partial matches like doing searchtext in candidate for candidate in [emp.<some_attributes>,..] or use levenshtein distance.

Upvotes: 1

Related Questions