[GIS] Python: Arcpy: Adding data to a shapefile

arcgis-desktoparcpy

Complete arcpy beginner here…

I have a shapefile with the fields CNTRY_NAME and GDP_HEAD.

I have a list in Python gdppop2002 = [['Country1, 234.1232341], [Country2, 23.2341234],...etc...]

I'm trying to write each float value in the list to the corresponding country row in the shapefile's attribute table. I need to check if each Country in gdppop2002 matches a CNTRY_NAME, and then write the float value in the list to GDP_HEAP. From a couple of hours of googling this appears to require creating an insert cursor, but I'm a little lost. Would anyone be able to point me in the right direction?

Best Answer

You can avoid most of the redundant conditional logic of Jason Miller's answer by converting your list into a dictionary:

gdppop2002_dict = {}
for pair in gdppop2002:
    gdppop2002_dict[pair[0]] = pair[1]

You can then iterate through the rows and update values directly from the dictionary:

with arcpy.da.UpdateCursor(fc, ['CNTRY_NAME', 'GDP_HEAP']) as cursor:
    for row in cursor:
        country = row[0]
        if country in gdppop2002_dict:
            row[1] = gdppop2002_dict[country]
            cursor.updateRow(row)

(Note that I've used arcpy.da.UpdateCursor, which only became available in ArcGIS 10.1. If you're on 10.0 or older, you'll have to use arcpy.UpdateCursor, which is less efficient and has slightly different syntax.)

Related Question