Geographic Information Systems Stack Exchange is a question and answer site for cartographers, geographers and GIS professionals. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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?

share|improve this question
up vote 2 down vote accepted

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.

share|improve this answer
    
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 4 '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

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")
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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