Select to view content in your preferred language

Create layer for each unique value of attribute(s) using layer definition

1607
3
03-15-2012 11:25 AM
TimHaverland4
Occasional Contributor
Hi,

Does anyone have a python script that:

- given a layer with multiple attributes (e.g. species, age)

will

- split the layer into multiple layers; one layer for each unique value of the given attributes (e.g. canine_10, feline_04)

and ideally

- does not do this by creating a new physical feature class or shapefile, but rather does it virtually via the layer definition
- groups the resulting layers into nested group layers (one level for each attribute)

Thanks for the advice,

Tim
Tags (2)
0 Kudos
3 Replies
JakeSkinner
Esri Esteemed Contributor
Hi Tim,

Here is some code to get your started:

fc = "Rivers_USA"

list = []
outList = []

# append values to list
rows = arcpy.SearchCursor(fc)
for row in rows:
    list.append(row.System)

del row, rows

# create unique list by removing duplicates
for n in list:
    if n not in outList:
        outList.append(n)

# create layer files
for n in outList:
    arcpy.MakeFeatureLayer_management(fc, "River_" + n, "\"SYSTEM\" = " + "'" + n + "'")
    arcpy.SaveToLayerFile_management("River_" + n, r"C:\temp\python\River_" + n + ".lyr")


This code creates layer files from a Rivers feature class based on an attribute called 'SYSTEM'.  All rivers that are part of the same system will be in one layer file.  You can then use the AddLayerToGroup function to add the layer files to a group layer.
0 Kudos
curtvprice
MVP Alum
Two thoughts -

1. You can easily undupe a python list like this.

>>> x
[4, 4, 1, 2, 2, 3]
>>> list(set(x))
[1, 2, 3, 4]
>>> 


2. I know this is the Python forum -- but want to note you could also do this task with no code using a unique fields iterator in model builder connected to the Make Feature Layer tool. The expression would include the model variable Value output by the iterator at each unique value of your field.

You could cap it off using the Collect Values tool piped into AddLayerToGroup to do that final step Jake suggests. However, my experience with model builder is it is usually in my interest not to "gild the lily" so to speak, and focus on setting it up to automate tasks - not create exceedingly complex tools. Though every version adds a little more oomph!
0 Kudos
TimHaverland4
Occasional Contributor
Thanks guys - that's very helpful and has me on my way. I did consider the model builder route but think the all-python method will afford me more control. If I'm successful creating a script tool that does this "virtual split layer on attribute(s)" function I'll share the code or working tool.
0 Kudos