Search code examples
pythonattributesarcgisfeature-selectionarcpy

Trying to create a simple select by attribute script based on an input


Trying to create a simple select by attribute script that will select based upon an input in a tool, in ARC Toolbox. My data is stored in a File database in a Feature Dataset called "Control", Feature Class is called "Monuments". Field is called "Township".

Here's the code

# Select Features base on Township

import arcpy 

mxd = arcpy.mapping.MapDocument("CURRENT")

Monuments = arcpy.mapping.ListLayers(mxd, "Monuments") [0]

TWN = arcpy.GetParameterAsText(0)

arcpy.SelectLayerByAttribute_management(Monuments, "NEW_SELECTION", "Monuments.Township" = TWN)

But getting Error message. "Keyword can't be an expression."

Any thoughts... Thanks in advance.


Solution

  • SHORT ANSWER

    arcpy.SelectLayerByAttribute_management(Monuments, "NEW_SELECTION", "Monuments.Township = '" + TWN + "'")
    

    EXPLANATION

    The way you tried it is basically the same as this:

    whereClause = "Monuments.Township" = TWN
    arcpy.SelectLayerByAttribute_management(Monuments, "NEW_SELECTION", whereClause)
    

    If you understand Python, you'll recognize that whereClause = "Monuments.Township" = TWN is not valid syntax. You cannot assign a value to "Monuments.Township", which is what your code tries to do. In the same way, you cannot pass "Monuments.Township" = TWN as a parameter. Instead, you have to build a string, like this: "Monuments.Township = '" + TWN + "'". That is valid syntax, as in the following:

    whereClause = "Monuments.Township = '" + TWN + "'"
    arcpy.SelectLayerByAttribute_management(Monuments, "NEW_SELECTION", whereClause)
    

    My short answer above does the same thing in one line of code instead of two.

    (My apologies to Python people, who can probably give a more precise explanation.)