I need to create a module to call to determine (true/false) if a field name in a feature class exists. My code works fine but returns a true or false for each field name, where I just need one true/false result for the entire feature class.
import arcpy
wrkspc = "C:/Pythonpro/FireDepartment.gdb"
arcpy.env.workspace = wrkspc
#Field Exists
def FieldExists(fcname,fieldname):
#fcname = input("Input feature class")
#fieldname = input("Input field name")
lstfields = arcpy.ListFields(fcname)
for field in lstfields:
if field.name == fieldname:
print("True")
if field.name != fieldname:
print("False")
4 Answers 4
Use in
to check if the field name is in your list of fields.
lstfieldNames = [f.name for f in lstfields]
if fieldname in lstfieldNames:
return True
return False
-
1Probably want to force the case to
upper()
orlower()
on both sides for reliable comparison.Vince– Vince2022年12月08日 12:41:28 +00:00Commented Dec 8, 2022 at 12:41
It can even be wrapped up into a short function using list comprehension.
def field_exists(dataset, field_name):
"""Determines the existence of a field in the specified data object.
Return true/false."""
return field_name.upper() in [f.name.upper() for f in arcpy.ListFields(dataset)]
You don't need to build a function for this, Esri already supports checking field existence with ListFields - ArcGIS Pro | Documentation:
Summary
Returns a list of fields in a feature class, shapefile, or table in a specified dataset. The returned list can be limited with search criteria for name and field type and will contain field objects.
The wild_card
parameter provides the search capability you seek. When a wildcard character isn't used, the parameter checks exact match. Also, it is case insensitive so you don't have to worry about capitalization.
Since an empty list is falsy, you can use the results from searching for a specific field directly in some other conditional statement.
# force result to boolean
bool(arcpy.ListFields(fcname,fieldname))
# use result in conditional statement
if arcpy.ListFields(fcname,fieldname):
...
Reading your question, you want to know if the field does or does not exist in the FC.
What if you counted the number of times the fieldname
exists in the FC. If it is greater that 0, it exists, if its 0 then it does not.
How about (not tested, but the flow is there).
i = 0
for field in lstfields:
if field.name == fieldname:
i += 1
if i > 0:
print ("True")
else:
print ("False")
-
Since duplicate names are not permitted in a feature class, counting is going to be much slower. You could assign a count of one and
break
in O(N/2) time, but this solution is O(N)Vince– Vince2022年12月08日 15:55:09 +00:00Commented Dec 8, 2022 at 15:55 -
Thanks @Vince. That makes sense.Keagan Allan– Keagan Allan2022年12月08日 20:15:32 +00:00Commented Dec 8, 2022 at 20:15
Explore related questions
See similar questions with these tags.
return True
when found (and areturn False
after the loop).