1

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?

PolyGeo
65.5k29 gold badges115 silver badges350 bronze badges
asked Jun 1, 2013 at 13:30
2
  • 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. Commented Jun 1, 2013 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. Commented Jun 1, 2013 at 21:00

2 Answers 2

4

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

answered Jun 1, 2013 at 22:37
1
  • Good call on changing this to a dict... I realize that my code wasn't completely ideal, was just trying to "make it understandable..." Commented Jun 5, 2013 at 11:14
1

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])
 cursor.updateRow(row)
 break;
 row = cursor.next()
answered Jun 1, 2013 at 17:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.