Sort the TOC in ArcMap alphabetically

I wanted to quickly create a kmz for a client which contained all of their asset data. It didn’t need to be in any order, but then I thought, why not alphabetical?

# @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( 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)

view raw
hosted with ❤ by GitHub

After trying out a few different ways, I decided to use an empty group layer as the anchor layer for sorting. One cannot add a group layer to the table of contents via Python, so unfortunately that step is a manual exercise.

This still beats manually moving dozens of layers up and down though 🙂

One thought on “Sort the TOC in ArcMap alphabetically

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.