Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knu2xs/8837800 to your computer and use it in GitHub Desktop.
Save knu2xs/8837800 to your computer and use it in GitHub Desktop.
For every unique value permutation in a feature class attribute field, create a unique layer displaying only these values utilizing a definition query.
# import arcpy...if already imported in your script, this is not necessary
import arcpy
def _uniqueValues(input_fc, field):
# search cursor wrapped in list comprehension creating list of all values
values = [row[0] for row in arcpy.da.SearchCursor(input_fc, (field))]
# pass list into set to get only unique values and return the result reverse sorted
return sorted(set(values), reverse=True)
def makeLayers(input_fc, attribute):
# for every value in the unique values list
for value in _uniqueValues(input_fc, attribute):
# ensure field has correct delmiters
sql_root = arcpy.AddFieldDelimiters(arcpy.Describe(input_fc).path, attribute)
# if the field is a string data type
if arcpy.ListFields(input_fc, attribute)[0].type == 'String':
# add single quotes around value and if there are single quotes in string, escape them
sql_tail = "'{0}'".format(value.replace("'","''"))
# for all other data types, just use the value
else:
sql_tail = "{0}".format(value)
# apply a definition query to the layer
sql = """{0} = {1}""".format(sql_root, sql_tail)
# create a layer and save the layer object to a variable, replacing / with - in the
# name so it actually gets added
layer = arcpy.MakeFeatureLayer_management(input_fc, value.replace("/", "-"), sql)[0]
# turn layer off to speed up loop, eliminating redrawing every time a layer is added
layer.visible = False
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment