3.2 Data Abstractions Python Hack
Categories: PythonHack(s) for intro to data abstractions in Python.
Python Lab: Simple DBs
In this lab, you’ll be working on a simple “database” system consisting of dictionaries. The idea here is to understand some basic CRUD actions and how you can use data abstractions (dictionaries in this case) to represent redundant, similar data under a unified structure.
You’ll have to do some research about some Python syntax for this!
You can complete the Python lab by simply running your code and getting your outputs in the Jupyter notebook.
# Our "database" is a list of dictionaries, each representing a record (e.g., a student)
# Lists allow us to store multiple records in a single variable, making it easy to manage collections of data.
db = [
{"name": "Alice", "age": 16, "grade": "A"},
{"name": "Bob", "age": 17, "grade": "B"},
{"name": "Charlie", "age": 16, "grade": "C"}
]
# Lists provide order and allow us to add, remove, or update records efficiently.
# Each element in the list is a dictionary, which abstracts the details of each student.
# Function to display all records
def display_db(database):
print("All records in the list:")
for i, record in enumerate(database):
print(f"Index {i}: {record}")
# Function to add a new record (students: implement input and append logic)
def add_record(database):
name = input("Enter student's name:")
age = int(input("Enter student's age:"))
grade = input("Enter student's grade:")
new_record = {"name": name, "age": age, "grade": grade}
database.append(new_record)
print("Record added successfully!")
# Function to find a record by name (students: implement search logic)
def find_record(database, search_name):
for record in database:
if record["name"] == search_name:
print("Record found:", record)
return
print("Record not found.")
# Function to update a record (students: implement update logic)
def update_record(database, search_name):
for record in database:
if record["name"] == search_name:
print("Current record:", record)
new_age = int(input("Enter new age:"))
new_grade = input("Enter new grade:")
record["age"] = new_age
record["grade"] = new_grade
print("Record updated successfully!")
return
print("Record not found.")
# Function to delete a record (students: implement delete logic)
def delete_record(database, search_name):
for record in database:
if record["name"] ==search_name:
database.remove(record)
print("Record deleted successfully!")
return
print("Record not found.")
# Example usage
display_db(db)
# Students: Uncomment and complete the following as you implement
# add_record(db)
# find_record(db, "Alice")
# update_record(db, "Bob")
# delete_record(db, "Charlie")