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)
db = [
    {"name": "Alice", "age": 16, "grade": "A"},
    {"name": "Bob", "age": 17, "grade": "B"},
    {"name": "Charlie", "age": 16, "grade": "C"}
]

# Function to display all records
def display_db(database):
    print("\nAll records in the list:")
    for i, record in enumerate(database):
        print(f"Index {i}: {record}")

# Function to add a new record
def add_record(database):
    name = input("Enter student name: ")
    age = int(input("Enter student age: "))
    grade = input("Enter student grade: ")
    new_record = {"name": name, "age": age, "grade": grade}
    database.append(new_record)
    print(f"✅ Record added: {new_record}")

# Function to find a record by name
def find_record(database, search_name):
    for record in database:
        if record["name"].lower() == search_name.lower():
            print(f"🔎 Found record: {record}")
            return record
    print("❌ Record not found.")
    return None

# Function to update a record
def update_record(database, search_name):
    for record in database:
        if record["name"].lower() == search_name.lower():
            print(f"Current record: {record}")
            record["age"] = int(input("Enter new age: "))
            record["grade"] = input("Enter new grade: ")
            print(f"✅ Record updated: {record}")
            return
    print("❌ Record not found.")

# Function to delete a record
def delete_record(database, search_name):
    for record in database:
        if record["name"].lower() == search_name.lower():
            database.remove(record)
            print(f"🗑️ Record deleted: {search_name}")
            return
    print("❌ Record not found.")

# Example usage
display_db(db)
# Uncomment the following lines to test interactively:
# add_record(db)
# find_record(db, "Alice")
# update_record(db, "Bob")
# delete_record(db, "Charlie")
# display_db(db)

All records in the list:
Index 0: {'name': 'Alice', 'age': 16, 'grade': 'A'}
Index 1: {'name': 'Bob', 'age': 17, 'grade': 'B'}
Index 2: {'name': 'Charlie', 'age': 16, 'grade': 'C'}