Select to view content in your preferred language

ArcPro 3.1.2 - How to search and update fields in arcpy.da.UpdateCursor using field names and not index?

672
3
12-12-2023 08:54 AM
VincentLaunstorfer
Frequent Contributor

Hi,

In a Python script, I use arcpy.da.UpdateCursor but I need to read/write into rows using field names and not indexes, because fields to update are given as a parameter by the user.

When creating the update cursor, I select all fields '*' in order manipulate any fields.

However, it is a pain to read/update rows using indexes (dozens of fields)! I know rows are tuples but I really need to access fields using field names.

I spent time looking at documentation and posts but cannot find any proper syntax.

Help would be appreciated

3 Replies
AlfredBaldenweck
MVP Regular Contributor

The row is a tuple, so you can use index(). Something along the lines of:

with arcpy.da.UpdateCursor(fc, "*") as cursor:
    for row in cursor:
        row[row.index("Field1")] = "Your value here"
        # etc.
        cursor.Update(row)

 

BlakeTerhune
MVP Regular Contributor

I use this little function to iterate the rows as a dictionary instead of a tuple.

def rows_as_dicts(cursor):
    colnames = cursor.fields
    for row in cursor:
        yield dict(zip(colnames, row))


with arcpy.da.SearchCursor(r'c:\data\world.gdb\world_cities', '*') as sc:
    for row in rows_as_dicts(sc):
        print row['CITY_NAME']
Clubdebambos
Frequent Contributor

There are a couple of very good answers here already to help you. If you are taking multiple field names in one parameter from a tool you can use the below to get them as a list of field names and then supply into your UpdateCursor.

 

 

## get multiple field names from user input
in_flds = arcpy.GetParameterAsText(0)

## split into a list of field names
in_flds = in_flds.replace("'", "").split(";")

with arcpy.da.UpdateCursor(in_table, in_flds) as cursor:
    ...

 

You can also factor in either from @AlfredBaldenweck or @BlakeTerhune to achieve your updates.

~ learn.finaldraftmapping.com