I am working on adding multiple new fields to a feature and then reclassify the values based on existing fields. Here is a part of the code where it does the reclassification and I am curious if there is a cleaner way to do this considering I have around 15 fields that I want to calculate which means I would have to write 15 codeblocks, expression and a line for CalculateField_management(my assumption). The below code just shows calculation field for 2 fields. I'm rather new to the backside of Python programming, so my current code is slightly cumbersome:

import arcpy
import os, sys

arcpy.env.workspace = r'C:\Project\2022\03\test.gdb'
shapefile = "31Dec2021"

expression_1 = "Reclass(!F_MaxIntCur!)"
expression_2 = "Reclass(!Test!)"

codeblock_1 = """
def Reclass(F_MaxIntCur):
    reclass = {
        1: 1,
        1.5: 1.5,
        2: 2,
        2.5: 10,
        3: 16,
        3.5: 56,
        4: 98,
        4.5: 624,
        5: 1152
    return reclass.get(F_MaxIntCur)
codeblock_2 = """
def Reclass(Test):
    reclass = {
        3: "Murder-Manslaughter",
        4: "Racism",
        5: "Robbery",
        6: "Aggravated Assault",
    return reclass.get(Test)

arcpy.CalculateField_management(shapefile, "CurrentViolIntScore", expression_1, "PYTHON_9.3", 
arcpy.CalculateField_management(shapefile, "CurrentViolDescription", expression_2, "PYTHON_9.3", 
  • 1
    Have you looked at using an UpdateCursor?
    – PolyGeo
    Apr 12, 2022 at 7:21
  • Though I have, I am not sure if changing this to upatecursor will simplify my code. I may be wrong, but it feels to me that the CalculateField_management approach is cleaner from a readability perspective, although I am struggling to achieve more with less code and number of repeated lines. Is there a way you could illustrate this with an example if you feel update cursor might be helpful?
    – Viv
    Apr 12, 2022 at 13:09

1 Answer 1


Yes, you can significantly reduce your code because update cursor lets you order fields to be updated. So for table like that:

enter image description here


with arcpy.da.UpdateCursor("FeatureClass",['from_A','to_A','from_B','to_b']) as cursor:
    for row in cursor:
        for i in range(len(lookups)):
            aDict = lookups[i]
            k = row[2*i]
            row[2*i+1] = aDict[k]

will result in:

enter image description here

Number of fields doesn't matter and your script will work much faster.

  • It's brilliant, thanks for illustrating this with an example. Definitely faster now with the revised implementation and I should dive into update cursors and its capabilities more deeply.
    – Viv
    Apr 13, 2022 at 8:42

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.