Day 46 - Saving Complex Data Structures Using Pickle

Using the Pickle Library to make saving data structures very simple.

Starter Code

dEmp = {
    "emp1": {
        "fname" : "Bill",
        "lname" : "Moseley",
        "age" : 49,
        "email" : "bill@bmoseley.com",
        "salary" : 98753.27
    },
    "emp2": {
        "fname" : "Dave",
        "lname" : "Smith",
        "age" : 25,
        "email" : "dsmith@bmoseley.com",
        "salary" : 45753.27
    }
}

def showMenu():
    print("""
    1. Add an Employee
    2. Terminate an Employee
    3. Give Everyone a Raise
    8. List Employees
    9. Exit the Program
    """)

def getID(emp_data):
    if not emp_data:
        return "emp1"

    emp_numbers = [int(key[3:]) for key in emp_data.keys() if key.startswith("emp")]
    next_id = max(emp_numbers, default=0) + 1
    return f"emp{next_id}"

def addEmployee(emp_data):
    strFName = input("What is the first name? ")
    strLName = input("What is the last name? ")
    intAge = int(input("What is the age? "))
    strEmail = input("What is the email? ")
    flSalary = float(input("What is the salary? "))

    dInner = {"fname":strFName, "lname":strLName, "age":intAge, "email":strEmail, "salary": flSalary}

    strID = getID(emp_data)

    emp_data[strID] = dInner

    print(f"New Employee Added: {strFName} {strLName}, ID: {strID}")

    return emp_data

def listEmp(emp_data):
    print("")
    for key in emp_data:
        print(f"ID: {key}".ljust(10) + f"{emp_data[key]['fname']} {emp_data[key]['lname']}".ljust(30) + f"{emp_data[key]['age']}".rjust(5) + f"{emp_data[key]['salary']:.2f}".rjust(15))

def termEmp(emp_data):
    print("\nHere are the employees:")
    listEmp(emp_data)
    print("\nWho would you like to terminate?")
    strId = input("Enter the ID here: ")
    if (strId in emp_data):
        dEmpT = emp_data.pop(strId)
        print(f"{dEmpT['fname']} {dEmpT['lname']} was terminated.")
        return emp_data
    else:
        print("This id doesn't exist.")

def giveAllRaise(emp_data):
    while True:
        strRaise = input("What is the raise percentage? (ex: 10): ")
        if (strRaise.isnumeric()):
            intRaise = int(strRaise)
            if (intRaise > 0 and intRaise <= 100):
                break
            else:
                print("You must enter a number between 1 and 100.")
        else:
            print("You must enter a number without decimals.")

    for key in emp_data:
        flSalary = emp_data[key]["salary"]
        flSalaryNew = flSalary * (1+(intRaise/100))
        print(f"{emp_data[key]['fname']} {emp_data[key]['lname']} got a raise from {flSalary:.2f} to {flSalaryNew:.2f}")
        emp_data[key]['salary'] = flSalaryNew

    return emp_data


print("*"*60)
print("*"+"Employee Database".center(58)+"*")
print("*"*60)
print("")

while True:
    showMenu()

    strMenu = input("What would you like to do? (Choose 1-9): ")

    if strMenu == "1":
        dEmp = addEmployee(dEmp)

    elif strMenu == "2":
        dEmp = termEmp(dEmp)

    elif strMenu == "3":
        dEmp = giveAllRaise(dEmp)

    elif strMenu == "8":
        listEmp(dEmp)

    elif strMenu == "9":
        break

    else:
        print("You need to enter a number for the menu choice.\n")


print("Thanks for using my program.")

Finished Code

import pickle, os

dEmp = {}

dStarter = {
    "emp1": {
        "fname" : "Bill",
        "lname" : "Moseley",
        "age" : 49,
        "email" : "bill@bmoseley.com",
        "salary" : 98753.27
    },
    "emp2": {
        "fname" : "Dave",
        "lname" : "Smith",
        "age" : 25,
        "email" : "dsmith@bmoseley.com",
        "salary" : 45753.27
    }
}

def saveData(dData):
    file = open("employee_data_pickle.txt", "wb")
    pickle.dump(dData, file)
    file.close()

def loadData(dData):
    if os.path.exists("employee_data_pickle.txt"):
        file = open("employee_data_pickle.txt", "rb")
        dLoaded = pickle.load(file)
        file.close()
    else:
        dLoaded = dData
        saveData(dData)

    return dLoaded

def showMenu():
    print("""
    1. Add an Employee
    2. Terminate an Employee
    3. Give Everyone a Raise
    8. List Employees
    9. Exit the Program
    """)

def getID(emp_data):
    if not emp_data:
        return "emp1"

    emp_numbers = [int(key[3:]) for key in emp_data.keys() if key.startswith("emp")]
    next_id = max(emp_numbers, default=0) + 1
    return f"emp{next_id}"

def addEmployee(emp_data):
    strFName = input("What is the first name? ")
    strLName = input("What is the last name? ")
    intAge = int(input("What is the age? "))
    strEmail = input("What is the email? ")
    flSalary = float(input("What is the salary? "))

    dInner = {"fname":strFName, "lname":strLName, "age":intAge, "email":strEmail, "salary": flSalary}

    strID = getID(emp_data)

    emp_data[strID] = dInner

    print(f"New Employee Added: {strFName} {strLName}, ID: {strID}")

    saveData(emp_data)

    return emp_data

def listEmp(emp_data):
    print("")
    for key in emp_data:
        print(f"ID: {key}".ljust(10) + f"{emp_data[key]['fname']} {emp_data[key]['lname']}".ljust(30) + f"{emp_data[key]['age']}".rjust(5) + f"{emp_data[key]['salary']:.2f}".rjust(15))

def termEmp(emp_data):
    print("\nHere are the employees:")
    listEmp(emp_data)
    print("\nWho would you like to terminate?")
    strId = input("Enter the ID here: ")
    if (strId in emp_data):
        dEmpT = emp_data.pop(strId)
        print(f"{dEmpT['fname']} {dEmpT['lname']} was terminated.")
        saveData(emp_data)
        return emp_data
    else:
        print("This id doesn't exist.")

def giveAllRaise(emp_data):
    while True:
        strRaise = input("What is the raise percentage? (ex: 10): ")
        if (strRaise.isnumeric()):
            intRaise = int(strRaise)
            if (intRaise > 0 and intRaise <= 100):
                break
            else:
                print("You must enter a number between 1 and 100.")
        else:
            print("You must enter a number without decimals.")

    for key in emp_data:
        flSalary = emp_data[key]["salary"]
        flSalaryNew = flSalary * (1+(intRaise/100))
        print(f"{emp_data[key]['fname']} {emp_data[key]['lname']} got a raise from {flSalary:.2f} to {flSalaryNew:.2f}")
        emp_data[key]['salary'] = flSalaryNew

    saveData(emp_data)

    return emp_data


print("*"*60)
print("*"+"Employee Database".center(58)+"*")
print("*"*60)
print("")

dEmp = loadData(dStarter)

while True:
    showMenu()

    strMenu = input("What would you like to do? (Choose 1-9): ")

    if strMenu == "1":
        dEmp = addEmployee(dEmp)

    elif strMenu == "2":
        dEmp = termEmp(dEmp)

    elif strMenu == "3":
        dEmp = giveAllRaise(dEmp)

    elif strMenu == "8":
        listEmp(dEmp)

    elif strMenu == "9":
        break

    else:
        print("You need to enter a number for the menu choice.\n")


print("Thanks for using my program.")