Get coded-value descriptions when accessing data with cursors

This question was recently asked on twitter:

@arcpy Can you point me to an example python script where a SearchCursor returns coded-value descriptions instead of the codes?”

With ArcGIS 10.1, the data access module contains functions for listing subtypes and listing domains. Here are recipes to get descriptions rather than just the codes either for subtypes or domains:

1. Get subtype descriptions

fc = r'c:\data\Portland.gdb\roads'
# Create a dictionary of subtype codes and descriptions.
desc_lu = {key: value['Name'] for (key, value) in arcpy.da.ListSubtypes(fc).iteritems()}
with arcpy.da.SearchCursor(fc, "SUBTYPEFIELD") as cur:
    for row in cur:
        print(desc_lu[row[0]])

2. Get domain descriptions

gdb = r'c:\data\Portland.gdb'
# Get the dictionary of codes and descriptions for the Floodplain_Rules domain.
desc_lu = [d.codedValues for d in arcpy.da.ListDomains(gdb) if d.name == 'Floodplain_Rules'][0]
with arcpy.da.SearchCursor(os.path.join(gdb, "floodplain"), 'RuleID') as cur:
    for row in cur:
        print(desc_lu[row[0]])

* NOTE: If you are running ArcGIS 10.1 with no service packs, just do the following to get a dictionary of subtype codes and descriptions. ListSubtypes was enhanced at ArcGIS 10.1 SP1.

desc_lu = arcpy.da.ListSubtypes(fc)

Advertisements