Sorting layers

471
2
Jump to solution
06-19-2024 02:02 PM
HusamOqer
Emerging Contributor

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
Frequent Contributor

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
Frequent Contributor

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
Emerging Contributor

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

0 Kudos