pythonclassdictionaryobject-oriented-database

Python: How to add information to a dictionary using a class, then print key and values of added dictionary entry


I'm working on the following assignment and am new to using classes to create/store objects:

Employee Management System: This exercise assumes you have created the Employee class for Programming Exercise 4. Create a program that stores Employee objects in a dictionary. Use the employee ID number as the key. The program should present a menu that lets the user perform the following actions: Look up an employee in the dictionary, Add a new employee to the dictionary, Change an existing employee’s name, department, and job title in the dictionary, Delete an employee from the dictionary, Quit the program. When the program ends, it should pickle the dictionary and save it to a file. Each time the program starts, it should try to load the pickled dictionary from the file. If the file does not exist, the program should start with an empty dictionary.

Everything went smoothly until I ran the program and was unable to print the information properly when using the employee lookup function. When running the code:

if ID in dictionary.keys():
    print(ID, ': ', dictionary[ID])

The output is:

1 :  <Employee.Employee object at 0x03520340>

I've attached an image of the program running when I add an employee and then try to look it up afterwards. I think there may be a problem with how I saved the data in the first place in the add function, or an issue in accessing the data in the lookup function. Is there a different way to print the contents of the dictionary for the specified ID? Have I stored the object properties improperly in the first place?


For reference, here is the rest of my code:

Employee.py (employee class in its own file):

class Employee:
    # Initialize Employee object
    def __init__(self, ID, name, department, job):
        self.__name = name
        self.__ID = ID
        self.__department = department
        self.__job = job

    # Set each object
    def set_name(self, name):
        self.__name = name

    def set_ID(self, ID):
        self.__ID = ID

    def set_dept(self, department):
        self.__department = department

    def set_job(self, job):
        self.__job = job

    # Get each object
    def get_name(self):
        return self.name

    def get_ID(self):
        return self.__ID

    def get_department(self):
        return self.__department

    def get_job(self):
        return self.__job


    def print(self):
        print("Name: " + self.__name + \
               ", ID Number: " + self.__ID + \
               ", Department: " + self.__department + \
               ", Job Title: " + self.__job)

EmployeeManagementSystem.py:

# Import necessary libraries
import pickle
import Employee
    
    
# STEP 1 = DEFINE FUNCTIONS FOR EACH CHOICE

# Lookup an employee
def lookup(dictionary):
    # Look up the ID number if it is in the dictionary
    ID = int(input('Enter the employee ID number: '))
    if ID in dictionary.keys():
        print(ID, ': ', dictionary[ID])
        print(dictionary.get(ID)) 
    else:
    print("That ID number was not found.")

    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed


# Add an employee
def add(dictionary):
    # Add a new employee
    ID = int(input('Enter the employee ID number: '))
    name = input('Enter the name of the employee: ')
    dept = input('Enter the employee department: ')
    job = input('Enter the employee job title: ')
  
    entry = Employee.Employee(ID, name, dept, job)
    dictionary[ID] = entry
    print('Employee added succesfully')
   
    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed
    
    
# Change an employee    
def change(dictionary):
    # If user-entered ID is in dictionary, allow them to change the info
    ID = input('Enter the employee ID you would like to change: ')
    if ID in dictionary.keys():
        name = input('Enter new employee name: ')
        newId = input('Enter new employee ID: ')
        dept = input('Enter new employee department: ')
        job = input('Enter new employee job title: ')
        entry = Employee.Employee(newID, name, dept, job)
        dictionary[ID] = entry
        print('Employee changed successfully.')
    else:
        print('That employee ID was not found.')
    
    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed
    
    
# Delete an employee
def delete(dictionary):
    # If user-entered ID is in dictionary, delete the entry
    ID = input('Enter the employee ID you would like to remove: ')
    if ID in dictionary.keys():
        del dictionary[ID]
        print('Employee removed successfully')
    else:
        print('That employe ID was not found.')
 
    # Offer the user the menu of choices again from main()
    proceed = True
    return proceed
    
    
# Save the dictionary and quit the program
def save_quit(dictionary):
    # Pickle the dictionary and save to a file
    output_file = open('employee_data.dat','wb')
    pickle.dump(dictionary,output_file)
    output_file.close
    
        
    # End the while loop in main() so program quits
    proceed = False
    return proceed
# STEP 2 - Main Function
def main():

    # Try to open the existing dictionary file
    try:
        input_file = open('employee_data.dat','rb')
        employee_dictionary = pickle.load(input_file)
        input_file.close()

    # If no such file exists, create a new dictionary
    except:
        employee_dictionary = {}


    # While loop to continue until user chooses to quit
    proceed = True
    while proceed:

        # Display user's option menu and ask for a choice
        print('\n Employee Management System\n')
        print('\t1. Lookup an employee')
        print('\t2. Add a new employee')
        print('\t3. Change an existing employee')
        print('\t4. Delete an existing employee')
        print('\t5. Save and Quit\n')

        option_choice = int(input('Enter an option to continue: '))

        # Map each choice to the functions below using a dictionary
        options = {1:lookup, 2:add, 3:change, 4:delete, 5:save_quit,}
        proceed = options[option_choice](employee_dictionary)



# STEP 3 - CALL MAIN
# Call the main function
main()

Solution

  • def lookup(dictionary):
        # Look up the ID number if it is in the dictionary
        ID = int(input('Enter the employee ID number: '))
        if ID in dictionary.keys():
            x=dictionary.get(ID)
            x.print()
    
        else:
            print("That ID number was not found.")
    
        # Offer the user the menu of choices again from main()
        proceed = True
        return proceed
    

    Since you already have a function for print call that and there is an error in the print function to fix that change the 'self.__id' to 'str(self.__ID)'

        def print(self):
            print("Name: " + self.__name + \
                   ", ID Number: " + str(self.__ID) + \
                   ", Department: " + self.__department + \
                   ", Job Title: " + self.__job)