3

This is my scenario:

  • List of names in a python list: a[]
  • A 1000 records shapefile with a column: 'name' (populated)
  • A second column called 'value'
  • ArcGIS environment (arcpy)

I want to update the column 'value' (i.e from 0 to 1) for all the shapefile records having a value in the column 'name' matching any of the list.

In terms of efficiency, I don't know which one is the best option:

A) Iterate through the list first; for each value of the list I start running through the shapefile asking for a match and do the update. Example: for 3 names; 3,000 reading operations on the shapefile.

B) Iterate through the shapefile first; for each record of the shapefile I look for a match on the list by iterating through the list each time. Example: for 3 names; 1,000 reading operations on the shapefile.

C) Use a dictionary instead, no list. Iterate through the shapefile first, and for each record, ask the dictionary for a value, if any, and do the update. Example: for 3 names; 1,000 reading operations on the shapefile.

1 Answer 1

5

If you have your values in a python list already, you only need to iterate through your shapefile. You can check if a value is in a list with if <value> in <list>:.

Example:

#full path to shapefile
shp = "C:\example\exampe.shp"

#check field
nameFld = "name"
#update field
valueFld = "value"
#update value
updateValue = 1

checkList = [...] #your values to check

import arcpy

#iterate rows in table
with arcpy.da.UpdateCursor (shp, [nameFld, valueFld]) as cursor:
    for name, value in cursor:
        #skip row if name value isn't in list
        if not name in checkList:
            continue

        #update
        row = (name, updateValue)
        cursor.updateRow (row)
2
  • Great use of a continue statement, +1 from me, shouldn't the #update be row[1]=updateValue? What happens to any other fields in the row if you set the row to the 2-value tuple? OP, name in checkList is case sensitive so beware of that situation and perhaps pre-process the checkList to all lower or upper case. Sep 24, 2015 at 23:12
  • 1
    @MichaelMiles-Stimson da.UpdateCursor only changes input fields. Two fields in, so my two-object tuple will update the two indicated fields, and all others will remain as they are. Sep 24, 2015 at 23:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.