Create a list of unique field values

This function can be used to return a unique list of field values. It takes advantage of the new data access module in ArcGIS 10.1.

def unique_values(table, field):
    with arcpy.da.SearchCursor(table, [field]) as cursor:
        return sorted({row[0] for row in cursor})

Here is an example of the return values:

>>> unique_values(r’C:\boston\city.gdb\crime’, ‘DAY’)
[u’Mon’, u’Sun’, u’Tues’, u’Wed’]

4 thoughts on “Create a list of unique field values

  1. While list comprehension is great for many purposes… leveraging numpy to do the heavy lifting can often improve performance. Included is a code snippet that uses the numpy.unique function. Of course, it also returns the unique values… further, the values are sorted. More importantly the speed is comparable to the list comp method, but the memory footprint is far smaller… when sorting 50,000 possible unique values the list comp function used 700 times more memory than the numpy function. Just an example of how important it is to read up on all the functions numpy makes available to you.

    def unique_values_2(table, field):
    data = arcpy.da.TableToNumPyArray(table, [field])
    return numpy.unique(data[field])

  2. Pingback: ArcPy Quick Tip: Find Unique Values in a Field Using the Python Window in ArcMap | wolfmapper

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s