Can I rewrite the Python code below using da.UpdateCursor ? I could not find an equivalent setValue() method for da.UpdateCursor to make the changes.
i = 0
fields= ['LastName','FirstName']
values= ['Jensen','Parky']rows = arcpy.UpdateCursor(table, where)
for row in rows:
while (i < len(fields)):
row.setValue(fields, values)
i += 1rows.updateRow(row)
del rows, row
Are there any arcpy methods to return the index of tableName.fieldName that we can plug into row[index] when using da.UpdateCursor?
Katie
Solved! Go to Solution.
import arcpy i = 0 fields = ["LastName", "FirstName"] values = ["Jensen", "Parky"] # Option A with arcpy.da.UpdateCursor(table, fields, where) as cursor: for row in cursor: while (i < len(fields)): row = values i+=1 i=0 cursor.updateRow(row) # Option B with arcpy.da.UpdateCursor(table, fields, where) as cursor: for row in cursor: for i,value in enumerate(values): row = value cursor.updateRow(row)
import arcpy i = 0 fields = ["LastName", "FirstName"] values = ["Jensen", "Parky"] # Option A with arcpy.da.UpdateCursor(table, fields, where) as cursor: for row in cursor: while (i < len(fields)): row = values i+=1 i=0 cursor.updateRow(row) # Option B with arcpy.da.UpdateCursor(table, fields, where) as cursor: for row in cursor: for i,value in enumerate(values): row = value cursor.updateRow(row)
Thanks Freddie, what if fields[0] and fields[1] are not the first and second fields in the attribute table? Will this still work?
For example,
OBJECTID | FirstName | LastName |
---|---|---|
1 | Jane | Doe |
row = value // i = 0 // row[0] is OBJECTID // fields[0] is FirstName
fields[0] and fields[1] correspond to fields = ["LastName", "FirstName"]
You decide which fields to include in the cursor. In doing so, you also decide the order of the fields in the cursor. Alternatively, you can include all fields by using '*', which will return all fields in the order found in the attribute table.
Consider a feature class with many fields, in any order, but you are interested in only "name", "age", and "address".
with arcpy.da.UpdateCursor("myFeatureClass",["name","age","address"]) as cursor: # you set cursor field order here for row in cursor: # loop through each row in the cursor print row[0] # name print row[1] # age print row[2] # address
vs.
with arcpy.da.UpdateCursor("myFeatureClass",["name","address","age"]) as cursor: # you set cursor field order here for row in cursor: # loop through each row in the cursor print row[0] # name print row[1] # address print row[2] # age
Thanks Darren, this makes perfect sense.
One challenge I was having was updating a 'lastUpdated' column to the localtime() without passing the 'lastUpdated' field to da.UpdateCursor first. I decided to append the value of localtime() to the end of the values array and 'lastUpdated' to the end of the fields array. It's working beautifully!