how to sort a ListLayers list?

6152
10
Jump to solution
06-21-2013 07:32 AM
JasonMills
New Contributor III
I get a list of layers from ArcMap. If I sort the layer list, it doesn't seem to sort. Here's a snippet of the code I use.
I attached a text file showing the results when I run the script from the python window in ArcMap. I also attached an image showing my table of contents with 219 layers.
When I use the code in a script, the results are a lot worst then the results show.
I'm using 10.1, sp1 on XP.

mxd = arcpy.mapping.MapDocument("CURRENT")
dfList = arcpy.mapping.ListDataFrames(mxd,"*")
df = dfList[0]
layerList = arcpy.mapping.ListLayers(mxd)
layerList.sort()
print str(len(layerList))
#print layerList
for layer in layerList:
    print layer.name
0 Kudos
10 Replies
ShaunWalbridge
Esri Regular Contributor
Great solution Curtis. This also can be a time that the collections module can come in handy, it provides OrderedDict for cases where you want things sorted:

import collections
d = dict((x.name, x) for x in layers)
od = collections.OrderedDict(sorted(d.items()))


Now od can be accessed sequentially and retains the relationship between name and layer.
0 Kudos