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?
Solved! Go to Solution.
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.
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.
It wasn't an option as I wanted to automate this, the script worked thank you so much!