Not Able to Pass Where Clause in SearchCursor in ArcPy

1698
4
Jump to solution
10-15-2018 09:24 PM
BehrouzHosseini
Occasional Contributor

Can you please take a look at this snippet and let me know why I am not able to properly pass the Where Clause ('"[NAME_1]" = Ohio') in SearchCursor?

import arcpy
from arcpy import env
def unique_values(table , field):
 with arcpy.da.SearchCursor(table, [field], '"[NAME_1]" = Ohio') as cursor:
 return sorted({row[0] for row in cursor})
uniques = unique_values(r'C:\arcgis\ArcTutor\AAA\src\USA.shp' , 'NAME_2')
for unique in uniques:
  print (unique)‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍

I am getting this error on runtime

Traceback (most recent call last):
File "<module1>", line 8, in <module>
File "<module1>", line 7, in unique_values
File "<module1>", line 7, in <setcomp>
RuntimeError: Unspecified error

Same error on this format as well

with arcpy.da.SearchCursor(table, [field], '"NAME_1" = Ohio') as cursor:
0 Kudos
1 Solution

Accepted Solutions
curtvprice
MVP Esteemed Contributor

This syntax is incorrect for shape file query expressions. The bracket delimeter you are using on the field name "[field]" is only used for personal geodatabases (.mdb), which BTW are not supported in 64-bit arcpy (Desktop background processing or ArcGIS Pro). Text literals also need to be surrounded by quotes.

'"NAME_1" = \'Ohio\''

There are some other issues with your code but we should probably start with that.

View solution in original post

4 Replies
curtvprice
MVP Esteemed Contributor

This syntax is incorrect for shape file query expressions. The bracket delimeter you are using on the field name "[field]" is only used for personal geodatabases (.mdb), which BTW are not supported in 64-bit arcpy (Desktop background processing or ArcGIS Pro). Text literals also need to be surrounded by quotes.

'"NAME_1" = \'Ohio\''

There are some other issues with your code but we should probably start with that.

BehrouzHosseini
Occasional Contributor

Thanks Curtis, the code is working now but can you please let me know what are the other issues which you noticed them?

0 Kudos
curtvprice
MVP Esteemed Contributor

I took another look at your code and it seems to look okay. One thing I've done to unique-ize the list is to use list(set(mylist)) but your method of using a dictionary ({}) is pretty neat and is probably very fast!

0 Kudos
BrittneyWhite1
Esri Contributor

I'll add that if you don't want to memorize the delimeters for each data type, you can always use the AddFieldDelimiters function:

See the section in the Specifying a query in Python help page: http://pro.arcgis.com/en/pro-app/arcpy/get-started/specifying-a-query.htm#GUID-98106084-6ECE-4647-A5...