Select to view content in your preferred language

arcpy.da.updatecursor with list

1191
2
02-07-2013 07:18 AM
RobertEhrman
Occasional Contributor
I'm using the arcpy.da module with the updatecursor class to populate specific values for specific fields in several hundred shapefiles. I'm specifiying the fields of interest for the updatecursor in a list but the catch is that the fields in the list are not all present in every shapefile.  So when the cursor trys to iterate through the fields of each shapefile and a field doesn't exist it throws an error saying the 'column is not specified'.  I tried several ways of verifying if the fields exists but have had not luck. Any suggestions, see code below.  Thanks

def field_vals():
    env.workspace = 'some_wspace'
    field_list = ['field1', 'field2', 'field3', 'field4', 'field5']
    val_list =[23,45,34,99,76]
    fcList = arcpy.ListFeatureClasses()
    for fc in fcList:
        with arcpy.da.UpdateCursor(fc,field_list) as cursor:
            for row in cursor:
                if row[4] == 0 and row[0] not in val_list and row[0] != 0:
                    row[4] = row[1]
                elif row[4] == 0 and row[1] not in val_list and row[1] != 0:
                    row[4] = row[2]
                elif row[4] == 0 and row[2] not in val_list and row[2] != 0:
                    row[4] = row[3]
                cursor.updateRow(row)
field_vals()
Tags (2)
0 Kudos
2 Replies
markdenil
Frequent Contributor
merge your field_list and val_list as a dictionary
masterDict = ['field1':23, 'field2':45, 'field3':34, 'field4':99, 'field5':76]
   
Then, as the first step in your "for fc in fcList:" loop,
use ListFields to get a list of fields for that fc (let's call it fcFieldList).

run through fcFieldList, checking which fields are keys in masterDict
build a field_list and a val_list from the master dictionary, using only fields present in the fcFieldList
and use the field_list and a val_list in the InsertCursor as you do in your code now.
0 Kudos
MathewCoyle
Honored Contributor
Here is one way of making sure each fc field in the list actually has a corresponding field in the data.
field_name_list = [field.name for field in arcpy.ListFields(fc) if field.name not in field_list]


I'd also add 0 to your val_list since you test for it each time.
0 Kudos