Additional data storage techniques
Using 2D Arrays to Emulate Database Tables
Two-dimensional (2D) arrays can be used to emulate database tables, where each row represents a record and each column represents a field.
Strictly speaking an array is of the same type, but python uses dynamic lists. These lists can hold vlaues taht are of different types which means we can keep the strings and numbers in the same array. However, we could still do this with a traditional array, we would just need to cast any string numbers into an int or float if they were not the correct data type for our needs.
Consider a database table storing student information, with fields for ID, Name, and Score:
# Define the 2D array
students = [
["ID", "Name", "Score"],
[1, "Alice", 85],
[2, "Bob", 90],
[3, "Charlie", 78]
]
# Accessing and printing the table
for i in range(1:len(students)):
for j in range(len(students[0])):
print(students[i][j])
Adding a Record
To add a new student record as we are using python lists we can use the append
method
students.append([4, "David", 92])
Accessing Specific Data
To access a specific piece of data, use row and column indices:
student_name = students[1][1] # Accessing "Alice"
print(student_name) # Output: Alice
Updating a Record
To update a student's score:
students[2][2] = 95 # Update Bob's score to 95
Key Points
- Emulation: 2D arrays emulate database tables effectively.
- Indexing: Use indices to access and modify data.
- Flexibility: Easily add, update, and manage records.
- Using 2D arrays in this way provides a simple and efficient method for handling structured data similar to a database table.