3

When working with search and update cursors, how do I call upon a specific row?

In this example:

import arcpy, os

# I want to find a row where the FID is 10
# print value field in the row where FID is 10

fc = 'c:\example.shp'
fields = ['Value']
with arcpy.da.SearchCursor(fc, fields) as cursor:
    for row in cursor:
        print(u'Row with FID = 10 has value {0}'.format(row[0])) 

However when using the code above, of course it prints out all the values, but I'm not quite sure what the easiest way to set the cursor to only print out the FID= 10 row would be.

In this example, I am trying to replace the value in the row where FID is 10 from where Value is 5 to Value is 10

fc = 'example.shp'
fields = ['Value']
cursor= arcpy.da.UpdateCursor(fc,fields)
try:
    for fid120 in cursor:
        row[0] = '10'
        row[1] = row[1].title()
        cursor.updateRow(row)
        print 'Row with FID = {0} has been updated to 25: {1}'.format(row[0], row[1])

    del cursor
except:
    print 'help'
del cursor

However again, I keep getting stuck with how to begin on calling the specific row to update it. One thing I tried to no avail is setting a variable equal to the FID I want to call, and creating an if statement akin to x = 10 'if row[0] = x' but that doesn't seem to work as well.

1
  • 4
    Read the help file for update cursor. What you want to set is the whereclause which limits what it returns.
    – Hornbydd
    Oct 21, 2021 at 0:31

2 Answers 2

8

As commented by @hornbydd try using a where clause on your cursor.

For example:

import arcpy

fc = 'c:\example.shp'
fields = ['Value']
where_clause = "FID = 10"
with arcpy.da.SearchCursor(fc, fields, where_clause) as cursor:
    for row in cursor:
        print(u'Row with {0} has value {1}'.format(where_clause,row[0])) 
1
  • 5
    I would add the obligatory warning about using FIDs from a shape file: Don't trust them not to change. If you want to call a specific row from a shapefile you will need to create a new column and fill it with unique numbers. Geodatabases (file, personal and enterprise) have an OID that can be trusted never to change, except in extreme situations, so using OBJECTID = 10 as a where clause is safe when dealing with those datasources. Oct 21, 2021 at 1:33
6

The question has been answered, this is just another way which is handy if you need to retrive many values. Load all your data into a dictionary:

import arcpy
fields = ['FID','BK']
fc = r'C:\GIS\data\indexrutor\index_5km.shp'
datadict = {key:value for key, value in arcpy.da.SearchCursor(fc, fields)}

datadict[10]
u'743_47_00'
datadict[1]
u'743_42_05'
datadict[0]
u'743_42_00'

enter image description here

Your Answer

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

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