Search code examples
pythondictionarytextdirectory

Python code that lets me lookup the name and ID from a text file


employees = {}

def load_employees():
    with open("employees.txt") as file:
        for line in file:
            id_num, full_name = line.strip().split(",")
            first_name, *_, last_name = full_name.split()  
            employees[(first_name, last_name)] = id_num  

def lookup_id(first_name, last_name):
    return employees.get((first_name, last_name), "ID not found")


def lookup_employee(id_num):
    if id_num in employees:
        return employees[id_num]
    else:
        return "Employee not found"


def main():
    load_employees()

    while True:
        print("\nChoose an option:")
        print("1. Lookup name by ID number")
        print("2. Lookup ID number by name")
        print("3. Quit")

        choice = input("Enter your choice: ")

        if choice == "1":
            try:
                id_num = int(input("Enter the ID number: "))
                result = lookup_employee(id_num)
                print(result)
            except ValueError:
                print("Invalid input. Please enter an integer ID number.")
        elif choice == "2":
            first_name = input("Enter the first name: ")
            last_name = input("Enter the last name: ")
            result = lookup_id(first_name, last_name)
            print(result)
        elif choice == "3":
            break
        else:
            print("Invalid choice. Please choose 1, 2, or 3.")

if __name__ == "__main__":
    main()

I am trying to write a code that lets you look up the name and ID of people from the project named employees.txt (saved in the same folder this Python file is saved) with the following data:

123 Bob Smith
345 Anne Jones
256 Carol Lee
845 Steve Robert Anderson
132 Jill Thompson

From the program's main function, we need to give the user the following options: lookup a name based on ID number, lookup an ID number based on a name, and quit the program.

OPTION 1: The user chooses to lookup a name based on ID number: Use a try/except and ask the user to enter an integer. If they don't enter an integer, print an error message. If they do enter an integer, call a function named lookup_employee which takes the id as a parameter. If an employee with the given id number is found, return the name. Otherwise, return the string “Employee not found” Back in the main, print the return result.

OPTION 2: The user chooses to lookup an ID based on the name: Ask the user to enter the first and last name (don't ask for the middle name). Call a function named lookup_id, which takes the first and last name as two separate strings. If an employee with the given first and last names is found, return the ID number. Otherwise, return the string "ID not found" Back in the main, print the return result.

OPTION 3: Exit the loop and quit the program.

I ran the code several times, and it's giving me errors.

Thank you in advance.


Solution

  • These were the fixes in the code

    1. Splitting line by <space> instead of <comma>
    2. Assigning the first item to id_num, and the remaining to full_name.
    3. Maintaining two separate dictionaries for both lookups, alternatively you can also reverse the keys, values of the employees dict.

    Here's the running code:

    employees = {}
    employees_names = {}
    
    def load_employees():
        with open("employees.txt") as file:
            for line in file:
                words = line.strip().split()
                id_num, full_name = int(words[0]), words[1:]
                first_name, *_, last_name = full_name
                employees[id_num] = [(first_name, last_name)]
                employees_names[(first_name, last_name)] = id_num
    
    def lookup_id(first_name, last_name):
        return employees_names.get((first_name, last_name), "ID not found")
    
    
    def lookup_employee(id_num):
        if id_num in employees:
            return employees[id_num]
        else:
            return "Employee not found"
    
    
    def main():
        load_employees()
    
        while True:
            print("\nChoose an option:")
            print("1. Lookup name by ID number")
            print("2. Lookup ID number by name")
            print("3. Quit")
    
            choice = input("Enter your choice: ")
    
            if choice == "1":
                try:
                    id_num = int(input("Enter the ID number: "))
                    result = lookup_employee(id_num)
                    print(result)
                except ValueError:
                    print("Invalid input. Please enter an integer ID number.")
            elif choice == "2":
                first_name = input("Enter the first name: ")
                last_name = input("Enter the last name: ")
                result = lookup_id(first_name, last_name)
                print(result)
            elif choice == "3":
                break
            else:
                print("Invalid choice. Please choose 1, 2, or 3.")
    
    if __name__ == "__main__":
        main()