Search code examples
pythonarcgisarcpy

Subgroup ArcPy list Query


Mornig, folks.

I have two equal sets of layers, disposed in subgroups in my ArcGIS Pro (2.9.0), as shown here. It's important that they have the same name (Layer1, Layer2, ...) in both groups. Now, I'm writing an ArcPy code that makes a Definition Query, but I want to do it only in one specific sub layer (Ex. Compare\Layer1 and Compare\Layer2).

For now, I have this piece of code that, I hope, can help.

p = arcpy.mp.ArcGISProject('current')
m = p.listMaps()[0]
l = m.listLayers()

for row in l:
    print(row.name)

COD_QUERY = 123

for row in l:
    if row.name in ('Compare\Layer1'):
        row.definitionQuery = "CODIGO_EOL = {}".format(COD_QUERY)
        print('ok')

When I write 'Compare\layer1' where's supposed to select only the Layer1 placed in the Compare group, the code doesn't work as expected and does the Query both in Compare\Layer1 and Base\Layer2. That's the exact problem tha I'm having.

Hope I can find some help with u guys. XD


Solution

  • The layer's name (or longName) does not include the group layer's name.

    Try using a wildcard (follow the link and search for listLayers) and filter for the particular group layer. A group layer object has a method listLayers too, you can again leverage it to get a specific layer.

    import arcpy
    
    COD_QUERY = 123
    
    project = arcpy.mp.ArcGISProject("current")
    map = project.listMaps()[0]
    
    filtered_group_layers = map.listLayers("Compare")
    
    if filtered_group_layers and filtered_group_layers[0].isGroupLayer:
    
        filtered_layers = filtered_group_layers[0].listLayers("Layer1")
    
        if filtered_layers:
    
            filtered_layers[0].definitionQuery = f"CODIGO_EOL = {COD_QUERY}"
    

    Or you can use loops. The key here is to filter out the group layers using isGroupLayer property before accessing the layer's listLayers method.

    import arcpy
    
    COD_QUERY = 123
    
    project = arcpy.mp.ArcGISProject("current")
    map = project.listMaps()[0]
    
    group_layers = (layer for layer in map.listLayers() if layer.isGroupLayer)
    
    for group_layer in group_layers:
    
        if group_layer.name in "Compare":
            
            for layer in group_layer.listLayers():
    
                if layer.name in "Layer1":
    
                    layer.definitionQuery = f"CODIGO_EOL = {COD_QUERY}"