AnsweredAssumed Answered

Permanently sort table by attribute

Question asked by CCweedcontrol on Apr 11, 2018
Latest reply on Apr 12, 2018 by balajiveera

I have a table that i need to get sorted base on a field (the STREET field). I don't want to create a new table i would like to work with the existing table. I am able to get the counter field populated with numbers and they look right but i can't see to get the "COUNTER" field sorted. I don't get an error with the following but it's not sorting by the COUNTER field.


import arcpy

#create order of 'Street'

lyr = 'C:\Temp\Default.gdb\CurrntRoadNamesTablePublic_1' # replace this with your layer name 
fields = ['STREET', 'OID@']

# set up a dictionary and counter 
dict = {} 
counter = 0 
# Use list comprehension to build a dictionary of Nummer/ObjectID tuple keys 
dict = {(row[0:]):0 for row in arcpy.da.SearchCursor(lyr, fields)} 
# Sort the dictionary keys and increase the counter values based on the key order 
for value in sorted(dict.keys()): 
    counter += 1 
    dict[value] = counter 
# Write back to the layer with an update cursor using the dictionary. Change 'COUNTER' to your counter field 
fields = ['STREET', 'OID@', 'COUNTER'] 
with arcpy.da.UpdateCursor(lyr, fields) as cursor: 
    for row in cursor: 
        row[2] = dict[(row[0],row[1])] 

with arcpy.da.UpdateCursor(lyr,"COUNTER",sql_clause=(None,"ORDER BY COUNTER")) as cursor:
    for row in cursor:
print 'Done'