I'm fairly new to python, so I'm having a little trouble with this. I want to iterate through a list of values, select the list values from a feature class, select from another feature class that intersects the first selection, and then calculate a field in the second selection based of the list index value. Here's the script I'm working on:

import arcpy
arcpy.env.workspace = r"C:workspace.gdb"

circuits = ["DC430", "DC431", "DC432"]

for i in range(len(circuits)):
    arcpy.SelectLayerByAttribute_management("Meters", "NEW_SELECTION", circuits[i])
    arcpy.SelectLayerByLocation_management("Parcels", "INTERSECT", "Meters", "", "NEW_SELECTION", "NOT_INVERT")
    arcpy.CalculateField_management("Parcels", "Circuit", "circuits[i]", "PYTHON_9.3", "")

How do I make this work the right way?

  • Select works on Layer. So use make feature layer and use SQL inside. Use select by location on newly created layer. – FelixIP Mar 16 '18 at 0:06

Iterate through your list of circuits and then create an SQL that matches the format you'd see in an ArcMap selection.

For text fields in a file geodatabase:


Your code would be something like this:

import arcpy
arcpy.env.workspace = r"C:workspace.gdb"

circuits = ["DC430", "DC431", "DC432"]
circuitFieldName = "YOURFIELDNAMEHERE"

for circuit in circuits:
    sql = "{} = '{}'".format (circuitFieldName, circuit)
    arcpy.SelectLayerByAttribute_management("Meters", "NEW_SELECTION", sql)
    arcpy.SelectLayerByLocation_management("Parcels", "INTERSECT", "Meters")
    arcpy.CalculateField_management("Parcels", circuitFieldName, '"{}"'.format (circuit))
  • Create layer is missing. – FelixIP Mar 16 '18 at 0:06
  • @ecartrace don’t forget to mark the answer as correct then. – Emil Brundage Mar 17 '18 at 6:01
  • Hi sir, I know my comment is too late. But would you care to explain what the "{} = '{}'".format is please? It seems like I see it on this sub from time to time. What's it called and how can I read up more on it? Thanks. – AndrewLebron Sep 5 '18 at 13:36
  • @Emil The first part of the string format() sql expression has the correct syntax, i.e., the quotes are correct - good work, and thanks! – user3467260 Jun 17 '20 at 5:45

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.