3

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.

5
  • 2
    What are you expecting "Monuments.Township" = TWN to do as a parameter?
    – jonrsharpe
    Commented Sep 9, 2015 at 15:07
  • It's the equation to select all the records in the monument layer that's township = the input parameter. Commented Sep 9, 2015 at 15:34
  • But that cannot be a keyword argument
    – jonrsharpe
    Commented Sep 9, 2015 at 15:45
  • so what would be the best way to write that argument? Commented Sep 9, 2015 at 16:21
  • I have absolutely no idea, I've never used arcpy. I'm just telling you that, from a basic Python syntax perspective, what you're writing now cannot work.
    – jonrsharpe
    Commented Sep 9, 2015 at 16:23

1 Answer 1

3

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.)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.