I want to make a code that select all unique values of a field in a attribute table. However, while everything in the code apparently works, I don't know how to add the current row in the Search Cursor in my selection.
layer = parameters[0].valueAsText
mylist = []
rows = arcpy.SearchCursor(layer, fields="Surveyor")
for row in rows:
value = row.getValue("Surveyor")
if value not in mylist:
mylist.append(value)
arcpy.SelectLayerByAttribute_management(layer, 'ADD_TO_SELECTION')
arcpy.AddMessage(mylist)
return
On the message (second last line), the program prints a list with 3 unique values. Yet, the code always select every single row. Makes sense, since there was no filter on my SelectLayer, so it just select the whole layer. So I tried using a field with Unique Values:
layer = parameters[0].valueAsText
mylist = []
rows = arcpy.SearchCursor(layer, fields="Surveyor, uniqueID")
for row in rows:
value = row.getValue("Surveyor")
myid = row.getValue("uniqueID")
if value not in mylist:
mylist.append(value)
arcpy.SelectLayerByAttribute_management(layer, 'ADD_TO_SELECTION', '"uniqueID" = myid')
arcpy.AddMessage(mylist)
return
But no success, it still selects the whole layer. So, how I make the SelectLayerbyAttribute to add to the selection only the row that the cursor is located?
2 Answers 2
"Old-style" search cursors are an artifact of the past. All supported versions of ArcGIS Desktop and Server offer Data Access cursors, which are faster and more Pythonic (list-oriented).
This is one way to rewrite your code, though there are options for faster runtime execution if you know that the number of IDs to be added is a relatively small set (e.g., less than 100-200).
The original problem was not placing the 'myid' value in the query expression.
layer = parameters[0].valueAsText
mylist = []
with arcpy.da.SearchCursor(layer, ['surveyor', 'uniqueID']) as cursor:
for row in cursor:
value = row[0]
myid = row[1]
if value not in mylist:
mylist.append(value)
filterexp = '"uniqueID" = {:d}'.format(myid)
arcpy.SelectLayerByAttribute_management(layer, 'ADD_TO_SELECTION', filterexp)
arcpy.AddMessage(mylist)
return
Found a solution:
layer = parameters[0].valueAsText
mylist = []
rows = arcpy.SearchCursor(layer, fields="surveyor, uniqueID")
for row in rows:
value = row.getValue("surveyor")
myid = row.getValue("uniqueID")
filterexp = '"uniqueID" = ' + str(myid)
if value not in mylist:
mylist.append(value)
arcpy.SelectLayerByAttribute_management(layer, 'ADD_TO_SELECTION', filterexp)
arcpy.AddMessage(mylist)
return
arcpy.SearchCursor
: Usearcpy.da.SearchCursor
instead.