Arcpy SearchCursor: list fields in ascending/descending order?

8290
4
Jump to solution
01-31-2018 08:02 AM
JaredPilbeam2
MVP Regular Contributor

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()
Tags (2)
0 Kudos
1 Solution

Accepted Solutions
RandyBurton
MVP Alum

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'):

View solution in original post

4 Replies
DanPatterson_Retired
MVP Emeritus

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

RandyBurton
MVP Alum

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'):
JaredPilbeam2
MVP Regular Contributor

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.

0 Kudos
RandyBurton
MVP Alum

Just use ASC, which is the default.  See this for more info: SQL reference for query expressions used in ArcGIS