1

I'm trying to extract a list of unique values in two fields in a shapefile. I think I am misunderstanding how the search cursor works, because I get the same error on which ever variable (x or y) I put second.

I'm following the answer here, and it works for just one field, but not 2+

Code:

with arcpy.da.SearchCursor(myshp, ['myid', 'myname']) as cursor:
    x = sorted({row[0] for row in cursor})
    y = sorted({row[1] for row in cursor})

Error:

y = sorted({row[1] for row in cursor})
IndexError: list index out of range
a11
  • 940
  • 10
  • 22

2 Answers2

2

You can use a generator expression for this. For example:

import arcpy

fc = r'C:\path\to\geodatabase.gdb\featureclass'

unique_list1 = set(row[0] for row in arcpy.da.SearchCursor(fc, 'myid')) unique_list2 = set(row[0] for row in arcpy.da.SearchCursor(fc, 'myname'))

Aaron
  • 51,658
  • 28
  • 154
  • 317
1

Although an existing answer works, it will not perform well for large feature classes and tables or when looking for unique values in many fields. Using defaultdict - collections - Container datatypes - Python 3.x documentation, one can loop through a cursor once and retrieve unique values for an arbitrary number of fields:

import arcpy
import collections

table = # path to feature class or table, or name of layer or table view fields = # list of field names to gather unique values

unique_values = collections.defaultdict(set) with arcpy.da.SearchCursor(table, fields) as cur: for row in cur: for i, value in enumerate(row): unique_values[cur.fields[i]].add(value)

for k, v in unique_values.items(): print(k) print(*sorted(i for i in v if i is not None), sep="\n")

bixb0012
  • 2,006
  • 1
  • 5
  • 18