Pynbbz Pynbbz - 4 months ago 19
Python Question

How can I sort my list by name/age separately?

Additionally, if I wanted to sort them by their age, how could I do so?
I tried myFile.sort(), but it crashes the code saying
"Object has no attribute 'sort' "

fileName = "GuestList.csv"
ACCESSMODE = "w"
name = " "
nbrGuest = " "

myFile = open(fileName, ACCESSMODE)
nbrGuest = input("How many guests do you have? ")
for index in range (int(nbrGuest)) :
name = input("Enter guest name: " ).capitalize()
age = input("Enter guest age: " )
myFile.write(name + "," + age + "\n")
myFile.close()

Answer

So the code is now split into two parts.

fileName = "GuestList.csv"
ACCESSMODE = "w"
name = " "
nbrGuest = " "


nbrGuest = input("How many guests do you have? ")
guest_list = []
for index in range(int(nbrGuest)):
    name = input("Enter guest name:\t").capitalize()
    age = input("Enter guest age:\t")
    guest_list.append((name, age))

guest_list.sort(key=lambda x: x[1])
with open(fileName, ACCESSMODE) as myFile:
    for guest in guest_list:
        myFile.write(guest[0] + "," + guest[1] + "\n")

The first part takes the user input and stores all information in a list of tuples. Each tuple looks like e.g., ('ALEX', '24'). After the list of guests is complete, it is sorted in place using the .sort() method based on the age of the guests (youngest first, use the ,reverse=True to reverse the order). Finally, the sorted names and ages are written to file that is managed by the with statement so that you don't have to worry about closing it or flushing it.