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’]

Advertisements

Calculate a unique value for each record

In this example, a unique value is calculated for each record starting with 1. The result is 1, 2, 3 … to the number of records. This is often necessary when you have to do some spatial operation and perform a join or relate using that field. It can also be useful when your table doesn’t have an OBJECTID field.

This code uses the data access module available with ArcGIS 10.1.

import arcpy
with arcpy.da.UpdateCursor(r"C:\Data\city.gdb\crime", "UID") as rows:
    for i, row in enumerate(rows, 1):
        row[0] = i
        rows.updateRow(row)