Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sorts the TOC in ArcMap alphabetically by using a temporary group layer for reference.
#
# @date 03/07/2015
# @author Cindy Williams
#
# Sorts the TOC in ArcMap alphabetically using
# a temporary group layer for reference. This group
# layer should be empty, and can be created anywhere
# in the TOC.
#
# For use in the Python window in ArcMap.
#
import arcpy
mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0] # Assuming one data frame
group_lyr = [lyr for lyr in arcpy.mapping.ListLayers(mxd) if lyr.isGroupLayer][0] # The temp group layer should be the only one
lyr_names = sorted(lyr.name for lyr in arcpy.mapping.ListLayers(mxd) if lyr.isFeatureLayer)
for name in lyr_names:
arcpy.mapping.MoveLayer(df, group_lyr, arcpy.mapping.ListLayers(mxd, name)[0], "BEFORE")
arcpy.mapping.RemoveLayer(df, group_lyr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment