collections.defaultdict
is perfect for this. If you use a counter, choosing the last would be trickier (not required in this instance, but potentially useful nonetheless).
from collections import defaultdict
import arcpy
ddict = defaultdict(list)
for key,oid in arcpy.da.SearchCursor("my fc", ["keyField", "OID@"]):
ddict[key].append(oid)
# Get the first distinct value. Use -1 to access the last
oids = sorted([v[0] for v in ddict.itervalues()])
oidField = arcpy.AddFieldDelimiters("my workspace", arcpy.Describe("my fc").oidFieldName)
sql = "{} IN ({})".format(oidField, ",".join(map(str, oids)))
With the following table, gridcode
is my keyfield:
| OBJECTID | gridcode |
|----------|----------|
| 1 | 6 |
| 2 | 6 |
| 3 | 5 |
| 4 | 5 |
| 5 | 6 |
| 6 | 6 |
| 7 | 5 |
| 8 | 1 |
| 9 | 5 |
>>> print(sql)
OBJECTID IN (1,3,8)
And for the last distinct value:
oids = sorted([v[-1] for v in ddict.itervalues()])
>>> print(sql)
OBJECTID IN (6,8,9)