Skip to content

Instantly share code, notes, and snippets.

@cindygis
Created July 3, 2015 06:32
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cindygis/35aa1108225212bc88d7 to your computer and use it in GitHub Desktop.
Save cindygis/35aa1108225212bc88d7 to your computer and use it in GitHub Desktop.
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