Welcome to Lesson 3 of Python from 0 to Hero! In the last lesson, we learned how to use control flow with if/else statements and loops, which are essential for making decisions and repeating tasks in your Python scripts.
In this lesson, we’ll dive into data structures, specifically focusing on:
- Lists – For handling collections of employee data.
- Dictionaries – For storing and managing information like employee names, IDs, and salaries.
Understanding these structures is crucial when dealing with employee databases, payroll information, and other HR-related tasks. By the end of this lesson, you’ll be able to efficiently manage employee information using Python.
1. Lists for Managing Employee Data
What is a List?
A list is a collection of items in a specific order. In HR, a list might represent employee names, salaries, or any other information you need to store about multiple people.
Here’s how you can create a simple list of employees:
# List of employee names
employees = ["Alice", "Bob", "Charlie", "Diana"]
# Display the list
print(employees)
Output:
['Alice', 'Bob', 'Charlie', 'Diana']
Accessing Items in a List
Each item in a list has an index (starting from 0). You can use these indices to access individual employees.
# Access the first employee
print(employees[0]) # Output: Alice
# Access the last employee
print(employees[-1]) # Output: Diana
Adding Employees to the List
If you hire a new employee, you can add them to the list using the append()
function:
# Add a new employee
employees.append("Eve")
print(employees)
Output:
['Alice', 'Bob', 'Charlie', 'Diana', 'Eve']
Removing Employees from the List
Similarly, when someone leaves the company, you can remove them from the list:
# Remove an employee
employees.remove("Charlie")
print(employees)
Output:
['Alice', 'Bob', 'Diana', 'Eve']
Example: Managing Employee Salaries
Let’s create two lists—one for employee names and another for their salaries. Then we’ll calculate and display the total payroll.
# Employee names and their respective salaries
employee_names = ["Alice", "Bob", "Diana", "Eve"]
salaries = [5000, 4000, 4500, 4800]
# Calculate total payroll
total_payroll = sum(salaries)
print(f"Total payroll for the company is: ${total_payroll:.2f}")
Output:
Total payroll for the company is: $18300.00
2. Dictionaries for Employee Records
What is a Dictionary?
A dictionary is like a real-life dictionary: it contains keys (the words) and values (the definitions). In HR terms, you can think of a dictionary as a collection of employee records, where each key could be an employee ID and the value could be their details (name, salary, etc.).
Creating a Dictionary for Employees
Let’s create a dictionary where each employee has an ID, and we store their name and salary as values.
# Employee dictionary
employees = {
101: {"name": "Alice", "salary": 5000},
102: {"name": "Bob", "salary": 4000},
103: {"name": "Diana", "salary": 4500},
104: {"name": "Eve", "salary": 4800}
}
# Display the employee dictionary
print(employees)
Output:
{101: {'name': 'Alice', 'salary': 5000}, 102: {'name': 'Bob', 'salary': 4000}, 103: {'name': 'Diana', 'salary': 4500}, 104: {'name': 'Eve', 'salary': 4800}}
Accessing Employee Information
You can use an employee's ID to access their specific information.
# Access Alice's details
alice = employees[101]
print(f"Alice's Salary: ${alice['salary']:.2f}")
Output:
Alice's Salary: $5000.00
Adding a New Employee to the Dictionary
When a new employee joins, you can add them to the dictionary by assigning their ID as a key and their information as a value.
# Add a new employee
employees[105] = {"name": "Frank", "salary": 4700}
print(employees[105])
Output:
{'name': 'Frank', 'salary': 4700}
Removing an Employee from the Dictionary
If an employee leaves the company, you can remove their record using the del
keyword.
# Remove Bob from the dictionary
del employees[102]
print(employees)
Output:
{101: {'name': 'Alice', 'salary': 5000}, 103: {'name': 'Diana', 'salary': 4500}, 104: {'name': 'Eve', 'salary': 4800}, 105: {'name': 'Frank', 'salary': 4700}}
3. Example: Payroll System Using Dictionaries
Let’s combine what we’ve learned to create a simple payroll system. The system will:
- Store employee data (name, salary, hours worked).
- Calculate the gross salary based on hours worked and overtime.
- Display a summary of payroll information.
Full Script: Payroll System
# Employee dictionary with hourly wages
employees = {
101: {"name": "Alice", "hourly_wage": 30, "hours_worked": 45},
103: {"name": "Diana", "hourly_wage": 25, "hours_worked": 38},
104: {"name": "Eve", "hourly_wage": 28, "hours_worked": 42},
105: {"name": "Frank", "hourly_wage": 27, "hours_worked": 40}
}
# Process payroll for each employee
for emp_id, details in employees.items():
name = details["name"]
hourly_wage = details["hourly_wage"]
hours_worked = details["hours_worked"]
# Calculate overtime if hours worked exceed 40
if hours_worked > 40:
overtime_hours = hours_worked - 40
regular_hours = 40
else:
overtime_hours = 0
regular_hours = hours_worked
# Calculate total pay
regular_pay = regular_hours * hourly_wage
overtime_pay = overtime_hours * hourly_wage * 1.5
gross_salary = regular_pay + overtime_pay
# Display payroll summary for each employee
print(f"Payroll Summary for {name} (ID: {emp_id})")
print(f"Regular Pay: ${regular_pay:.2f}")
print(f"Overtime Pay: ${overtime_pay:.2f}")
print(f"Gross Salary: ${gross_salary:.2f}")
print("-------------------------------")
Script Breakdown:
- We create a dictionary with each employee’s name, hourly wage, and hours worked.
- We loop through the dictionary, calculating the regular pay and overtime pay.
- The script prints out a payroll summary for each employee, showing their gross salary, overtime pay, and regular pay.
Example Output:
Payroll Summary for Alice (ID: 101)
Regular Pay: $1200.00
Overtime Pay: $225.00
Gross Salary: $1425.00
-------------------------------
Payroll Summary for Diana (ID: 103)
Regular Pay: $950.00
Overtime Pay: $0.00
Gross Salary: $950.00
-------------------------------
Payroll Summary for Eve (ID: 104)
Regular Pay: $1120.00
Overtime Pay: $84.00
Gross Salary: $1204.00
-------------------------------
Payroll Summary for Frank (ID: 105)
Regular Pay: $1080.00
Overtime Pay: $0.00
Gross Salary: $1080.00
-------------------------------
Conclusion
In this lesson, we explored how to:
- Use lists to store and manage collections of employee data.
- Use dictionaries to store more complex employee records (name, salary, hours worked).
- Combine these data structures in a practical payroll processing system.
These tools will help you efficiently manage employee data and automate repetitive tasks. In the next lesson, we’ll dive into file handling, where you’ll learn to store and retrieve employee records from files, further automating your HR workflows.
If you have any questions or suggestions, feel free to drop a comment! Keep practicing, and see you in the next lesson!
Top comments (0)