4

In arcpy.SearchCursor for row in rows I can return row.fieldname statically, but if fieldname is a variable, I don't know how to return the row.value of that variable dynamically.

for example:

    sortfield = something
    rows = arcpy.Searchcursor(feature)

    fieldlist = arcpy.ListFields(directory)
    for row in rows:

      for f in fieldlist:
        if f.name == something:                       
          id = row.something
3
  • 1
    I'm struggling to understand your question. Do you want to return all the values of a single field?
    – sgrieve
    Commented Nov 8, 2012 at 14:39
  • Sorry - I seem to have missed out the searchcursor. I want to Loop through my featureclass using a searchcursor, displaying the value of row.something (something being a softcoded variable rather than a hard coded fieldname) Commented Nov 8, 2012 at 14:53
  • Please update your question to reflect that.
    – R.K.
    Commented Nov 12, 2012 at 8:10

2 Answers 2

11

@sgrieve's answer works for ArcMap 10.1 users with the data access (da) module. You can do this in earlier versions of Arc by using row.getValue. I'll modify sgrieve's example:

import arcpy

fc = 'C:\\shp\\islands.shp'
fields = ['FID','Id'] #insert whatever variable you need into this list

cursor = arcpy.SearchCursor(fc)
for row in cursor:
    print row.getValue(fields[0]), row.getValue(fields[1])
del row, cursor

You don't have to feed in the field names via list necessarily, but if you're working with datasets with unknown field names, you could get them in a list using the ListFields method and feed them in this way.

0
2

There are a number of arguments you can supply when using a searchcursor, which are outlined in the arcGIS help. To perform this task I would use the data access module, arcpy.da.SearchCursor, to speed up the operation.

If you provide a list of fieldnames to the searchcursor it will allow you to specify softcoded fieldnames as you require:

import arcpy

fc = 'C:\\shp\\islands.shp'
fields = ['FID','Id'] #insert whatever variable you need into this list

with arcpy.da.SearchCursor(fc, fields) as cursor:
    for row in cursor:
        print row[0], row[1]

This sample prints out the values in the fields specified in the list, but of course more complex operations can be performed on these values now that they have been exposed.

2
  • Thanks! As a sidequest could this be done using a non- da.SearchCursor method? Commented Nov 8, 2012 at 15:28
  • 3
    the da module is only available in 10.1, so this code won't work in 10.0
    – DavidF
    Commented Nov 8, 2012 at 15:58

Your Answer

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

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