How do I get a specific field name with arcpy?

3635
9
Jump to solution
01-05-2021 02:26 PM
by Anonymous User
Not applicable

I have a geodatabase table with three fields. After creating a list of fields with arcpy, how do I reference just the third field to acquire the fieldname for use in the next arcpy statement?

0 Kudos
2 Solutions

Accepted Solutions
DanPatterson
MVP Esteemed Contributor

ListFields—ArcGIS Pro | Documentation

assuming

field_names = [f.name for f in arcpy.ListFields(featureclass)]
third_fld = field_names[2]

... sort of retired...

View solution in original post

DavidPike
MVP Frequent Contributor

Further to Dan's point, you should probably pass third_fld within a list as the last argument.

arcpy.JoinField_management(fc_in, joinfld1, gdb_table, joinfld2, [third_fld]) 

View solution in original post

0 Kudos
9 Replies
JoshuaBixby
MVP Esteemed Contributor
>>> l = ["field1", "field2", "field3"]
>>> l[2]
'field3'
>>>
DanPatterson
MVP Esteemed Contributor

ListFields—ArcGIS Pro | Documentation

assuming

field_names = [f.name for f in arcpy.ListFields(featureclass)]
third_fld = field_names[2]

... sort of retired...
jrneyulu
New Contributor

This will fail when cursor is fetching mentioned fields only, better to Collect field names from Cursor not from feature class.

0 Kudos
DavidPike
MVP Frequent Contributor

What do you mean by 'mentioned fields'?

0 Kudos
by Anonymous User
Not applicable

This is similar to the procedure I came up with yesterday after many trials and errors:

third_fld = arcpy.ListFields(gdb_table)[2]

I could get it to print the name of the correct field with:

print('Field is {0}.'.format(thrid_fld.name))

I could not, however, pass the field name into the JoinField tool with:

arcpy.JoinField_management(fc_in, joinfld1, gdb_table, joinfld2, third_fld)  

 I'm guessing I am missing something and to simply reference 'third_fld' in the JoinField statement is generating the error:

Runtime error
Traceback (most recent call last):
File "<string>", line 65, in <module>
File "c:\program files (x86)\arcgis\desktop10.8\arcpy\arcpy\management.py", line 6587, in JoinField
raise e
RuntimeError: Object: Error in executing tool

0 Kudos
DavidPike
MVP Frequent Contributor

Further to Dan's point, you should probably pass third_fld within a list as the last argument.

arcpy.JoinField_management(fc_in, joinfld1, gdb_table, joinfld2, [third_fld]) 
0 Kudos
by Anonymous User
Not applicable

I got this to work. A couple of issues - it never worked in ArcMap but did in Pro. Plus I changed the interpreter within Pycharm to ver 3.7. And added the brackets around third_fld.

Thanks everyone!!

Pam

DanPatterson
MVP Esteemed Contributor

third_fld ...thrid_fld ... third_fld

Consistency? Is this a copy-paste issue on your pare or is that what you have in your code?


... sort of retired...
0 Kudos
by Anonymous User
Not applicable

Typing issue - the code was correct.

0 Kudos