0

How do you pass conditional statements from a list into a data access module update cursor?

I am using ArcGIS v10.3.1.

a = r"...\Default.gdb\New_Shapefile"
ConList = ["r[1] >= 1"]
with arcpy.da.UpdateCursor(a, ["Id", "apples"]) as uCur:
    for r in uCur:
        if ConList[0]:
            r[0] = 99
            uCur.updateRow(r)

Result is shown, highlighted rows should default to zero

Result is shown, highlighted rows should hold the pre-existing value of zero.

  • 1
    why not query the field directly in the cursor. arcpy.da.UpdateCursor(in_table, field_names, {where_clause}, {spatial_reference}, {explode_to_points}, {sql_clause}) , so right after your fields put your query, then you will only be working with the records that you want to update rather than every record in the table. – ed.hank Apr 5 '18 at 18:44
  • Suggest you look at the help file on UpdateCursor this will give you examples of how to use the whereclause as eluded to by @ed.hank – Hornbydd Apr 5 '18 at 18:47
  • Because when applying this within the larger program I am writing, multiple conditional statements need to be used when determining the value which should be assigned within the update cursor. Moreover, the conditional statements need to change depending on which feature class the program is processing. Thus the conditional statements in the larger program are organized in lists. I could use the whereclause, but this would then mean I would have to use a large number of cursor loops though a very large feature class. – pyRsq Apr 5 '18 at 18:51
  • 2
    Create a function, call the function for each row. – BERA Apr 5 '18 at 19:26
  • Thanks BERA, I knew there was a simple solution. I don't know why I didn't think to try that. Need more coffee today I guess. Cheers. – pyRsq Apr 5 '18 at 19:39
0

To clarify so you don't repeat that problem, the problem lies with your if statement, as it will always be True as written. Example:

>>> ConList = ["a = b"]
>>> if ConList[0]: print true

The above prints "true" but should not print anything. Your if statement simply evaluates whether or not there is a value in ConList[0]; it isn't using the expression within it.

The above advice of a function is the way to go.

1

Without rewriting your code, you can use eval() to evaluate your expression string as Python.

a = r"...\Default.gdb\New_Shapefile"
ConList = ["r[1] >= 1"]
with arcpy.da.UpdateCursor(a, ["Id", "apples"]) as uCur:
    for r in uCur:
        if eval(ConList[0]): # evaluates your expression
            r[0] = 99
            uCur.updateRow(r)

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.