1

What is the fastest/cleanest way to get a collection of rows that are selected in a certain layer? For some background, I am trying to hide selected features in a specified layer.

Is there a way to get the selected rows by using a layer object which is provided by a script parameter?

Eyrofire
  • 331
  • 4
  • 9

2 Answers2

3

You can use the following to grab the OID of selected features within a layer.

FIDSet = arcpy.Describe(layer).FIDset
records = [int(FID) for FID in FIDSet.split(";")] if FIDSet else []

This way, you can make a selection, grab the OIDs, and clear selection.

arcpy.SelectLayerByAttribute_management(layer, "CLEAR_SELECTION")

It should occur quickly, so the selection may not be visible.

Jason Scheirer
  • 18,002
  • 2
  • 53
  • 72
Barbarossa
  • 5,797
  • 27
  • 61
  • This works. Just to note, the code will throw an exception because the string given by arcpy.Describe(layer).FIDset is a series of id codes. You want: map(int,arcpy.Describe("test").FIDset.split("; ")) – Eyrofire Mar 04 '14 at 18:39
  • @Eyrofire this is cool but dont work if there is no selection but you can map with function and return type int or None for string (empty selection) and create a v = filter(None, (map(ignore_if_string,arcpy.Describe(fl).FIDset.split("; ")))) – GeoStoneMarten Dec 14 '15 at 16:47
0

I tested and fixed a little bit the @Eyrofire proposition and fix part to get a count of seleted entities based on the FID

def ignore_if_string(s):
    """ return None if string value can be cast to int """
    try:
        return int(s)
    except ValueError:
        return

def selected_count(fl):
    """ return count of selected entities """
    return len(filter(None, (map(ignore_if_string,arcpy.Describe(fl).FIDset.split("; ")))))

test:

>>> if selected_count(fl):
...     arcpy.SelectLayerByAttribute_management(fl, "CLEAR_SELECTION")
...
>>> selected_count(fl)
0
>>> arcpy.SelectLayerByAttribute_management(fl, "NEW_SELECTION", """"NODE_ID" = 0""")
<Result 'GPL0'>
>>> selected_count(fl)
4777825
>>> if selected_count(fl):
...     arcpy.SelectLayerByAttribute_management(fl, "CLEAR_SELECTION")
GeoStoneMarten
  • 1,165
  • 10
  • 26