1

I am attempting to create a single set of all the attributes read from a field on a feature class. This is my code so far:

import arcpy
workspace = arcpy.mapping.MapDocument("CURRENT")
cursor = arcpy.da.SearchCursor("FireStations",['CITY'])
s1 = set()

for row in cursor:
    s1.add(row)
    print(s1)

The issue I am having is that it seems to create a new set with all the attributes within the field for every new attribute. So instead of one single set of all the attributes I get one set with all the attributes for every row in the specified field. I know this is most likely an issue with my for loop, anyone have any thoughts on fixing this issue?

PolyGeo
  • 65,136
  • 29
  • 109
  • 338

1 Answers1

2

In order to get all the unique values from a field, you could use a set comprehension on the SearchCursor:

import arcpy
workspace = arcpy.mapping.MapDocument("CURRENT")
unique_values = {r[0] for r in arcpy.da.SearchCursor("FireStations", ['CITY'])}
print(unique_values)

Alternatively, if you would still like to use a for loop, you would need to use the set.add() method. Python sets have never had append method. Mind the indentation of the print() - you would most likely want to print the output set of unique values just once. Also, each row would be a tuple with of length 1 meaning you would need to access the actual value using the index - in this case row[0] as indexing in Python starts with 0.

import arcpy
workspace = arcpy.mapping.MapDocument("CURRENT")
cursor = arcpy.da.SearchCursor("FireStations", ['CITY'])
s1 = set()

for row in cursor:
    s1.add(row[0])
print(s1)
fatih_dur
  • 4,983
  • 2
  • 16
  • 35
Alex Tereshenkov
  • 29,912
  • 4
  • 54
  • 119
  • yes you're right .add not .append. Also can't believe I missed that my print function was inside the for loop, thanks a lot. – M. C. Griffin Oct 25 '18 at 19:39
  • No worries, glad it worked out! Finding issues in the code and fixing them is part of programming, too! :) good luck with learning arcpy! There is a great collection of resources - make sure to review them - excellent bedtime reading ;) https://gis.stackexchange.com/questions/53816/learning-arcpy – Alex Tereshenkov Oct 25 '18 at 19:41
  • Also recommend a book https://www.amazon.com/dp/1589483715/ - going through this one will give you 99% of what you could possibly need. – Alex Tereshenkov Oct 25 '18 at 20:40