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?

  • 1
    The online help contains code examples resources.arcgis.com/en/help/main/10.1/index.html You will need to AddField, then use an update cursor. Peruse the documentation for details. – user681 Jun 1 '13 at 16:47
  • gdppop2002 looks more suited to be stored as a dictionary than a list of short lists so could be worth considering if refactoring your code. – PolyGeo Jun 1 '13 at 21:00

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]

(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.)

  • Good call on changing this to a dict... I realize that my code wasn't completely ideal, was just trying to "make it understandable..." – Jason Miller Jun 5 '13 at 11:14

Try this:

import arcpy

gdppop2002 = [["Country1", 234.1232341], ["Country2", 23.2341234]]
fc = "c:/YourFolder/YourShapeName.shp"
field1 = "CNTRY_NAME"
field2 = "GDP_HEAD"

cursor = arcpy.UpdateCursor(fc)
row = cursor.next()
while row:
    countryName = row.getValue(field1)
    for subList in gdppop2002:
        if subList[0] == countryName:
            row.setValue(field2, subList[1])

    row = cursor.next()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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