I have python code that uses arcpy.SearchCursor to look for unique values in a field (Native_Species, in my case), and put them into a list. Then I use list comprehension to remove None values, sort the list, and print. This code works.

# Create empty list, use .SearchCursor to populate list with unique valuesmyList = []rows = arcpy.SearchCursor(monitoring)for row in rows:if row.Native_Species not in myList:myList.append(row.Native_Species)# Use list comprehension to remove None values in listres = [i for i in myList if i]# Sort list and printres.sort()print(*res, sep = '\n')

I would like to put this code into a function, where I can list only unique values across multiple fields in a given feature class. This is what I have tried:

def listUnique(fc, fields):myList = []with arcpy.da.SearchCursor(fc, fields) as cursor:for row in cursor:if row.fields not in myList:myList.append(row.fields)res = [i for i in myList if i]res.sort()print(*res, sep = '\n')

This gives me an error "'tuple' object has no attribute 'fields'".

How should I put my working code into a function, where I can specify a given input feature class, and a list of fields within that feature class, and get back a list of only unique values across those fields?

Thank you!

1

Best Answer


The output is not real pretty. Might be more useful to create a unique value list for every feature class column. Hopefully this will give you some ideas to get what you need.

import arcpy# set the workspace to the geodatabase the feature class is inarcpy.env.workspace = r'\path\to\your\geodatabase.gdb'def uniqueValues(fc):# create a list of unique values from all rows and columns in a feature class#create an empty list to store all values in the feature classtableList = []#Get all values in the feature class and append them to tableListfcList = arcpy.ListFeatureClasses(fc)for fc in fcList:with arcpy.da.SearchCursor(fc, "*") as cursor:for row in cursor:for value in row:tableList.append(value)print('The list length of all values is ' + str(len(tableList)))# Create an empty list to store the unique values in the feature classuniqueList = []# use set to drop duplicatesuniqueSet = set(tableList)print('The list length of unique values is ' + str(len(uniqueSet)))# put the items from the set back into a list. add all values to the list as strings to avoid data type problemsfor item in uniqueSet:uniqueList.append(str(item))# remove none values from the listuniqueList = [i for i in uniqueList if i]# sort the listuniqueList = sorted(uniqueList)print(*uniqueList, sep = '\n')# call the function and enter the name of the feature class as the parameteruniqueValues('Enter Feature Class Name')