1

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?

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

1 Answer 1

3

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:

YOURFIELDNAME = 'FIELD VALUE'

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))
4
  • Create layer is missing.
    – FelixIP
    Mar 16, 2018 at 0:06
  • @ecartrace don’t forget to mark the answer as correct then. Mar 17, 2018 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.
    – Bowen Liu
    Sep 5, 2018 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! Jun 17, 2020 at 5:45

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.