0

I've used SearchCursor to return the single value of a record (8 digit number)

for row in arcpy.da.SearchCursor(table, ['PID']):
if row[0] is not None:
        ID = row[0]
    break

Now I would like to use 'ID' in a query.

arcpy.SelectLayerByAttribute_management(Table2, "NEW_SELECTION",'ID' == ID)

This is not a valid expression and I'm not sure how to make the keyword ID usable.

2

The concept you are looking for is "string formatting" or "string interpolation"

If you're on python 2.7:

arcpy.management.SelectLayerByAttribute(Table2, "NEW_SELECTION", 'ID = {}'.format(ID))

Or

arcpy.management.SelectLayerByAttribute(Table2, "NEW_SELECTION", 'ID = ' + str(ID))

Or

arcpy.management.SelectLayerByAttribute(Table2, "NEW_SELECTION", 'ID = %s' % ID)

In modern pythons, you can do any of those plus my preferred method:

arcpy.management.SelectLayerByAttribute(Table2, "NEW_SELECTION", f'ID = {ID}')

Note

These assume your "ID" variable is an integer. If it's not, you'd change them like so (check the use of double and single quotes):

arcpy.management.SelectLayerByAttribute(Table2, "NEW_SELECTION", "ID = '{}'".format(ID))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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