Select to view content in your preferred language

Sorting layers

299
2
Jump to solution
06-19-2024 02:02 PM
HusamOqer
New Contributor II

Hello,

I am working on a script that plot many layers to an aprx file and do some other stuff and I would like to sort those layers based on the naming (Descending or Ascending order).

Any recommendation on how to do that using arcpy for GIS Pro?

 

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
HaydenWelch
Occasional Contributor II

HaydenWelch_0-1718889849895.png

Is this not an option? If you need to automate it, you can use the mapping module.

 

 

import arcpy

project = arcpy.mp.ArcGISProject("CURRENT")

for mp in project.listMaps():
    # Sort Layers by Name
    sorted_layers = sorted(mp.listLayers(), key=lambda lyr: lyr.name)
    previous_layer = None
    
    # Iterate through sorted layers and move them to the top of the map
    for lyr in sorted_layers:
        # Use existing first layer as reference for sorted first layer
        if not previous_layer:
            mp.moveLayer(mp.listLayers()[0], lyr, "BEFORE")
        else:
            mp.moveLayer(previous_layer, lyr, "AFTER")
        previous_layer = lyr

 

If you have group layers and want to preserve internal group layer ordering, you will have to update the lyr.name sory key to lyr.longName so the group layer name is included in the sort.

 

View solution in original post

2 Replies
HaydenWelch
Occasional Contributor II

HaydenWelch_0-1718889849895.png

Is this not an option? If you need to automate it, you can use the mapping module.

 

 

import arcpy

project = arcpy.mp.ArcGISProject("CURRENT")

for mp in project.listMaps():
    # Sort Layers by Name
    sorted_layers = sorted(mp.listLayers(), key=lambda lyr: lyr.name)
    previous_layer = None
    
    # Iterate through sorted layers and move them to the top of the map
    for lyr in sorted_layers:
        # Use existing first layer as reference for sorted first layer
        if not previous_layer:
            mp.moveLayer(mp.listLayers()[0], lyr, "BEFORE")
        else:
            mp.moveLayer(previous_layer, lyr, "AFTER")
        previous_layer = lyr

 

If you have group layers and want to preserve internal group layer ordering, you will have to update the lyr.name sory key to lyr.longName so the group layer name is included in the sort.

 

HusamOqer
New Contributor II

It wasn't an option as I wanted to automate this, the script worked thank you so much! 

0 Kudos