Jacob Daniels Jacob Daniels - 5 months ago 7
Python Question

Changing a specific value from a list into an integer

I've been trying to have a program print out a sorted list depending on the requested item. When I request the list from the CSV file I'm not sure how to set only 2 of the 4 values into an integer as when it displays in the program the numbers are treated as strings and it doesn't sort properly.

Eg:

['Jess', 'F', '2009', '6302']

['Kat', 'F', '1999', '6000']

['Alexander', 'M', '1982', '50']

['Bill', 'M', '2006', '2000']

['Jack', 'M', '1998', '1500']

def sortD(choice):
clear()
csv1 = csv.reader(open('TestUnsorted.csv', 'r'), delimiter=',')
sort = sorted(csv1, key=operator.itemgetter(choice))
for eachline in sort:
print (eachline)
open('TestUnsorted.csv', 'r').close()

#From here up is where I'm having difficulty

with open('TestSorted.csv', 'w') as csvfile:
fieldnames = ['Name', 'Gender', 'Year','Count']
csv2 = csv.DictWriter(csvfile, fieldnames=fieldnames,
extrasaction='ignore', delimiter = ';')
csv2.writeheader()
for eachline in sort:
csv2.writerow({'Name': eachline[0] ,'Gender': eachline[1],'Year':eachline[2],'Count':eachline[3]})
List1.insert(0, eachline)
open('TestSorted.csv', 'w').close


Here's what my TestUnsorted file looks like:

Jack,M,1998,1500

Bill,M,2006,2000

Kat,F,1999,6000

Jess,F,2009,6302

Alexander,M,1982,50

Answer
sort = sorted(csv1, key=lambda ch: (ch[0], ch[1], int(ch[2]), int(ch[3])))

That will sort the last two values as integers.

EDIT:

Upon further reading the question, I realize choice is the index of the list that you want to sort on. You could do this instead:

        if choice < 2: # or however you want to determine whether to cast to int
            sort = sorted(csv1, key=operator.itemgetter(choice))
        else:
            sort = sorted(csv1, key=lambda ch: int(ch[choice]))