Selecting and reselecting ObjectID/OID using arcpy
I was searching for something else when I stumbled upon a solution to another problem I had a while back.
With arcpy you can Describe
a layer to find its FIDSet
– a string containing the OIDs of all selected features. I’ve found this list to be useful in scripts so I can go back to previously selected features, or perform analysis based on selected features etc., however there was no way to pass an updated FIDSet
back to the layer – it is read only.
Enter the getSelectionSet()
and setSelectionSet()
, which are methods attached to the Layer class. Where FIDSet
returns a string of OIDs, getSelectionSet
returns a python list which can be looped through and modified as required, and then passed back (again as a python list) to update the selection by using setSelectionSet
. I’ve found this to be much faster at selecting features than passing a query with all OIDs to the standard selectLayerByAttribute
.
In my test run, looping through 5000 at a time to a total of 55000 records, using FIDSet
and SelectLayerByAttribute
took close to 2 minutes, and using setSelectionSet
took only 24 seconds.
import arcpy
FeatureLayer = "MyLayer"
myObjectIDList = [27, 35, 58, 87, 985, 1287] # List of ObjectIDs to select from my FeatureLayer
lyr = arcpy.mapping.Layer(FeatureLayer)
lyr.setSelectionSet("NEW", myObjectIDList) # Select features