Skip to content

Instantly share code, notes, and snippets.

@AlexArcPy
Created November 9, 2016 16:08
Show Gist options
  • Save AlexArcPy/c966e19b539cbe403485db3f26411eb6 to your computer and use it in GitHub Desktop.
Save AlexArcPy/c966e19b539cbe403485db3f26411eb6 to your computer and use it in GitHub Desktop.
Using Python named tuples for feature class records
from collections import namedtuple
import arcpy
fc = r'C:\Program Files (x86)\ArcGIS\Desktop10.4\TemplateData\TemplateData.gdb\USA\states'
#creating a defintion of a named tuple with fields from feature class
fields = [field.name for field in arcpy.ListFields(fc)]
state = namedtuple('StateFeature',field_names=fields)
#generating named tuples for features in feature class
states = [state._make(f) for f in [f for f in arcpy.da.SearchCursor(fc,fields)]]
#printing states and their two letter code filtering and sorting along the way
states = filter(lambda x: x.POP2000>10000000, states)
states = sorted(states,key=lambda x: x.POP2000,reverse=True)
print type(states[0])
#<class '__main__.StateFeature'>
for state in states:
print state.STATE_NAME, state.STATE_ABBR
print
#could be rewritten to a shorter version
for state in sorted(filter(lambda x: x.POP2000>10000000,states),
key=lambda x: x.POP2000,reverse=True):
print state.STATE_NAME, state.STATE_ABBR
#California CA
#Texas TX
#New York NY
#Florida FL
#Illinois IL
#Pennsylvania PA
#Ohio OH
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment