Sort layers in TOC using arcpy

4489
3
Jump to solution
12-31-2015 05:00 AM
Yaron_YosefCohen
Occasional Contributor II

Hi,

i try to sort layers in the TOC, in ascending or by name alphbetical with this code:

import arcpy

mxd = arcpy.mapping.MapDocument(r"D:\desktop\Project\project.mxd")
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")
    print name +' sorted'
   
arcpy.mapping.RemoveLayer(df, group_lyr)

and got:

>>> 
land use sorted
river sorted
>>> 

but the TOC do't sorted. For clarity, i saw this question in arcgis 10.0 - Arc GIS 10.1 - How to sort Layers ascending at TOC in "List by drawing order" - Geogra...

I work with arc view 10.3. I know it possible with extension, but i have no extensions.

Is it possible to do it with python?

Tags (3)
0 Kudos
1 Solution

Accepted Solutions
WesMiller
Regular Contributor III

I don't see where you saved the document. You may want to use savACopy() till you get what you want.

MapDocument—Help | ArcGIS for Desktop

View solution in original post

3 Replies
WesMiller
Regular Contributor III

I don't see where you saved the document. You may want to use savACopy() till you get what you want.

MapDocument—Help | ArcGIS for Desktop

DanPatterson_Retired
MVP Emeritus

also, it makes little sense to sort things alphabetically... for example

...  landuse, river   in this scenario, you could have agricultural land over top of the river

...  fire station, ownership .... where did the fire station go?

... bridge, river .... the Chunnel?

Order things by geometry first, then conceptually within each grouping to ensure that you don't obliterate features that should be seen

0 Kudos
Yaron_YosefCohen
Occasional Contributor II

in this project i don't need to sort geometry first. I do need to sort alphabetically and also by numbers.

0 Kudos