1

I'm looking for the best way to reference a layer in the TOC using arcpy and, if it is possible, that is different than the following:

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]
layers = arcpy.mapping.ListLayers(df)

Reference layers:

mylayer1 = layers[0]
mylayer2 = layers[1]
...

It comes out that in some cases I may not know the index in the list [0], 1, etc... so I need to reference it using other identifiers.

In previous versions I used to reference the layer first as a file in disk, then add the layer in the TOC and, at last, reference it using the same variable. However, in versions such as 10.2, it does not work and I need to reference in other ways, but the way explained in the example above does not convince me. Other examples such as the ones explained in the following post are usefull in some cases (click here for an example but I think there should be a simplest way that does not require loop structures...

So, is there a better way?

1
  • What exactly is it you want to do? Are you doing arcpy.Mapping commands or do you want to run GP tools against layers in the ToC?
    – KHibma
    Mar 24, 2015 at 20:28

2 Answers 2

5

Here's the ListLayers documentation

ListLayers(map_document_or_layer, {wildcard}, {data_frame})

You can use a wildcard if you know the name of the layer.

mxd = arcpy.mapping.MapDocument("CURRENT")
df = arcpy.mapping.ListDataFrames(mxd)[0]

road_layer = arcpy.mapping.ListLayers(mxd, "Road", df)[0]
river_layer = arcpy.mapping.ListLayers(mxd, "River", df)[0]

Where "River", or "Road" is the name of the layer in the TOC.

0

There are a wide means of referencing layers within a table of contents. Just check out the various layer properties available. For example, if you wish to find a layer by name, perform your ListLayers and then make use of an if lyr.name == "mylayer": statement in your for loop.

1
  • Well, I was precisely referring to a method that does not use loops. But thank you.
    – Maik
    Apr 9, 2015 at 21:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.