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?

2 Answers 2

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.

2
  • 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
    Commented Mar 4, 2014 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("; ")))) Commented Dec 14, 2015 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")

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.