Using arcpy.da.SearchCursor, how do you sort data in either ascending or descending order?
I noticed the old arcpy.SearchCursor had sort_fields.
arcpy.SearchCursor(dataset, {where_clause}, {spatial_reference}, {fields}, {sort_fields})
I have a script that uses arcpy.da.SearchCursor to create a list of table fields. The "D" in the function of line 8 is meant to put it in descending order, but it does not.
env.workspace = r'\\gisfile\GISstaff\Jared\ModelBuilder\TEST folder\TESTGDB.gdb'
#variables
intable = "ElectionResults_Nov2016"
tbList = [] #create list
#use cursor to get all unique values in field, and list them in ascending order
for row in arcpy.da.SearchCursor(intable, "ContestTitle", "D"):
if row[0] not in tbList:
tbList.append(row[0])
EDIT: I've also been looking into sorted. It's a matter of placing it in the cursor, though.
sorted()
Solved! Go to Solution.
As Dan Patterson suggests, you need to use the sql_clause in the search cursor:
for row in arcpy.da.SearchCursor(intable, "ContestTitle", sql_clause=(None,'ORDER BY ContestTitle DESC'):
Apparently the da.searchcursor supports ordering within an sql clause.
There are several code examples here
http://pro.arcgis.com/en/pro-app/arcpy/data-access/searchcursor-class.htm
As Dan Patterson suggests, you need to use the sql_clause in the search cursor:
for row in arcpy.da.SearchCursor(intable, "ContestTitle", sql_clause=(None,'ORDER BY ContestTitle DESC'):
Thanks both Dan and Randy. That was the solution.
Interestingly, what you have there works to order the fields in a descending order. On the other hand, the only way I got them to order in ascending order was not to have anything after ...ContestTitle:
for rows in arcpy.da.SearchCursor(intable, field, sql_clause=(None, "ORDER BY ContestTitle")):
I tried "ORDER BY ContestTitle ASCE" and it threw an errror.
Just use ASC, which is the default. See this for more info: SQL reference for query expressions used in ArcGIS