How to access Field Names

5012
12
Jump to solution
08-04-2017 08:52 AM
VishalShah2
Occasional Contributor II

So I am working on a custom tool that uses one of the existing fields to make a selection by attribute. For example, say I have a feature called Target Feature and in the feature, the fields were called Field1, Field2, Field3, and Field4. I am trying to get a variable to be set equal to arcpy.ListFields('Target Feature') and then to check if a field name is in that feature. The selection I want wasn't working, no selection was being made actually. Here's what I was leaning towards but it didn't work for me:

import arcpy

fieldList = arcpy.ListFields('Target Feature')
fieldName = ['Field3']
fieldValue = ['%45B%']

if fieldName in fieldList:
    if fieldValue in fieldName:
        arcpy.SelectLayerByAttribute_management ('Target Feature', NEW_SELECION, "Field3 LIKE " + "'" + str(fieldValue) + "'")‍‍‍‍‍‍‍‍‍

But this isn't working for me. Any help is appreciated!

0 Kudos
12 Replies
ClintonDow1
Occasional Contributor II

In the query the 'Field3' value gets replaced with the value within that column, for each row. So its checking if the value of the Field3 column matches any of those 3 strings and if so the row gets selected.

The join is just a python function on the String type (as you can see I'm defining a string inline: ', ' then calling the function .join() on it), concatenating the 3 strings from the list together, separated by a comma and space into a single string. This has to be done because the query is a single string. 

If you used

fieldValue = '%45B%', '%46A%', '%47C%'# ('%45B%', '%46A%', '%47C%'‍)

It will work as well, but will give you a Tuple instead of a list. This works fine in the current situation, but if you had a script with variable fieldValues, a Tuple wouldn't work because the values within are not mutable - this is why I suggested the list.

Does that clear it up?

VishalShah2
Occasional Contributor II

It does! Thank you so much Clinton!

ClintonDow1
Occasional Contributor II

My pleasure

0 Kudos