ArcPy – How to Update Attributes from List of Values in Excel or CSV Table

arcpyfields-attributes

I need a Python program regarding update attributes. I have 20 shapefiles and in each shapefile, attributes to be updated based another field
Example values

My requirement is to update the codes in CODE field as per the name (Example list is given right side) for 50000 features, like if name is AAA, then code will be 419, if name is ABC, then code is 420.

I have 850 different codes and I want to update all 850 at once in shapefile. I can update two or three values by using below code but I don't know how to update 850 codes.

import arcpy
from arcpy import env


env.workspace = r"C:\\data\test.shp"   
env.workspace = fc
fclist = arcpy.ListFeatureClasses()

for fc in fclist :
   fields = ["name", "code"]

   with arcpy.da.UpdateCursor(fc, fields) as cursor:
      for row in cursor:
          if row[0] == "AAA"
              row[1] =  419
          elif:
          if .row[1] == "BBB"
              row[6] = 420
              cursor.updateRow(row)

print "codes updated"

If I want to update all 850 codes, need to write if…else statement 850 times to update all codes. I have saved all names and codes in Excel. So instead of writing many if else statements, please help how to update all codes based on name by using Excel or CSV file.

Best Answer

If you need to write a lot of if statements you should consider using a dictionary instead. Code below will read a csv file and create a dictionary of names and codes and then use the dictionary in the Updatecursor for all shapefiles in a folder. Backup your data Before you try it:

import arcpy, csv

shapefile_folder = r'C:\folder'
arcpy.env.workspace = shapefile_folder
shapefile_fields_to_update = ["name","code"]

codefile = r"C:\Program123\codes.csv"

with open(codefile, 'r') as f:
    reader = csv.reader(f)
    dict = {k:v for (k,v) in reader} #Dictionary of names and codes is created here

for shapefile in arcpy.ListFeatureClasses():
    with arcpy.da.UpdateCursor(shapefile, shapefile_fields_to_update) as cursor:
        for row in cursor:
            if row[0] in dict:
                row[1]=int(dict[row[0]]) #And used here
                cursor.updateRow(row)
            else:
                print "Name {0} not found in the dictionary, no update made for this name".format(row[0])

enter image description here

Related Question