Wednesday, August 24, 2011

Sorting Dictionary Values

Let's say you want to find the largest feature in your feature class.  There are many ways to do this, but here is one simple way using dictionaries.

rows = arcpy.SearchCursor(infc)
featDict = {}
for row in rows:
   feat = row.getValue(shapefieldname)
   featDict[row.getValue("ObjectID")] = feat.area
del row, rows
for w in sorted(featDict,key=featDict.get,reverse=True):
   print w, featDict[w] # prints the largest area first and gives the OID value to get the feature
del featDict

The first entry in the dictionary will be the highest shape area. If you wanted the smallest area, you would set reverse=False.

The key here is the sorted(), which more information can be found here.