[GIS] Using da.SearchCursor to get count of unique values in a field

arcgis-desktoparcpycursor

Is it possible to use arcpy.da.SearchCursor() to get a count of unique features in a field without a dictionary?

So, by this I mean if I have a field called TEXT which contains 10,000 rows populated with either A or B. Can I use the da.SearchCursor to quickly give me the count for the total amount of A in TEXT and B in the TEXT?

I know it is possible to use Summary Statistics or the Get Count tool but these involve having to make a feature layer and then selecting features or kicking out a table. I looking to have a few steps as possible in my script 🙂

Best Answer

Use collections.Counter:

import collections

with arcpy.da.SearchCursor(feature_class, field) as cur:
    count_of_items = collections.Counter(row[0] for row in cur)

print "Sorted items"
print "----"

for item in sorted(count_of_items.items(), key=lambda x:x[1]):
    print "{0:>12} {1:>4}".format(item[0], item[1])
Related Question