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
asked Oct 16, 2020 at 2:39

2 Answers 2

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'))
answered Oct 16, 2020 at 2:56
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")
answered Feb 25, 2023 at 17:39

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.