I am aware of the sorted() function but I am having a little trouble using it/implementing it in my code. I have a database containing student records such as Name, address, age etc. When the user selects "4" the program runs the function to Display all records saved in the database and I desire it to be sorted alphabetically. My function works and displays the records, just not alphabetically. How could I take advantage of the sorted() function to make my code display the records alphabetically? Any help would be greatly appreciated.
rom ShowAllRecords import show_record
from deleteRecord import delete_student
from showRecord import view_records
from createRecord import add_record
global student_info
global database
"""
Fields :- ['Student ID', 'First name', 'Last Name', 'age', 'address', 'phone number']
1. Create a new Record
2. Show a record
3. Delete a record
4. Display All Records.
5. Exit
"""
student_info = ['Student ID', 'First name', 'last name', 'age', 'address', 'phone number']
database = 'file_records.txt'
def display_menu():
print("**********************************************")
print(" RECORDS MANAGER ")
print("**********************************************")
print("1. Create a new record. ")
print("2. Show a record. ")
print("3. Delete a record. ")
print("4. Display All Records. ")
print("5. Exit")
while True:
display_menu()
choice = input("Enter your choice: ")
if choice == '1':
print('You have chosen "Create a new record."')
add_record()
elif choice == '2':
print('You have chosen "Show a record"')
show_record()
elif choice == '3':
delete_student()
elif choice == '4':
print('You have chosen "Display ALL records"')
view_records()
else:
break
print("**********************************************")
print(" RECORDS MANAGER ")
print("**********************************************")
ViewRecords function-
import csv
student_info = ['Student ID', 'First name', 'last name', 'age', 'address', 'phone number']
database = 'file_records.txt'
def view_records():
global student_info
global database
print("--- Student Records ---")
with open(database, "r", encoding="utf-8") as f:
reader = csv.reader(f)
for x in student_info:
print(x, end='\t |')
print("\n-----------------------------------------------------------------")
for row in reader:
for item in row:
print(item, end="\t |")
print("\n")
input("Press any key to continue")
I know I should use the sorted function, just not sure where/how to properly implement it within my code
Sample Run:
Blockquote
RECORDS MANAGER
1. Create a new record.
2. Show a record.
3. Delete a record.
4. Display All Records.
5. Exit.
Enter your option [1 - 5]: 4 You have chosen "Display ALL records in alphabetical order by last name." Would you like the registry sorted alphabetically in Ascending or Descending order? (A or D): D
Last Name: Hunt First Name: Alan Student ID: 875653 Age: 23 Address: 345 Ocean Way Phone number: 3334445454
Last Name: Farrow First Name: Mia Student ID: 86756475 Age: 22 Address: 34 Lotus Ct Phone number: 9994448585
Done! Press enter to continue. returning to Main Menu.
CodePudding user response:
You already know you need the sorted
function. Think about what you need to sort: all the records in your csv file, and the key to use to sort: Let's say by last name and then first name. See the documentation for more detail on the key
argument to sorted
. Since you want to sort by two items, you can create a tuple containing these two items as your key. In this case, for any student record r
, the last name is the third element (r[2]
) and the first name is the second element (r[1]
), so our key needs to be the tuple (r[2], r[1])
.
So in the function where you read the records, instead of printing them immediately, read all the records first, then sort them, and then print them:
def view_records():
# These are not necessary since you never set these variables in the function
# You can access those variables without global
# global student_info
# global database
print("--- Student Records ---")
with open(database, "r", encoding="utf-8") as f:
for x in student_info:
print(x, end='\t |')
print("\n-----------------------------------------------------------------")
reader = csv.reader(f)
student_records = sorted(reader, key=lambda r: (r[2], r[1]))
for row in student_records:
print(*row, sep="\t |")
input("Press any key to continue")
CodePudding user response:
By default the sorted()
function will sort a list alphabetically, so you could read the lines in the file into a list, call sorted on the list, the print that list line by line with something like this:
with open(database, "r", encoding="utf-8") as f:
reader = csv.reader(f)
# make a list of all lines in the database
line_list = []
for line in reader:
line_list.append(line)
# print the list
line_list = sorted(line_list)
for line in line_list:
print(line)
I'm not exactly sure that's the correct way to go line by line for a database file but you get the idea. Another thing you can do with sorted is pass it a function that determines exactly what you sort, so say if you have 3 columns in your database and for each line you split the row into a list of 3 items you could do this:
def func(x):
return x[2]
data = [[a,b,c],[d,e,f],[g,h,i]]
sorted_data = sorted(data, key=func)
to sort the data by the third column. This is also used when you want to sort by some manner that's not alphanumeric.
Finally, for questions on basic functions like this I highly recommend geeksforgeeks as it usually has good basic examples and descriptions of things like this.