[GIS] Getting all (or selected) values from single field in table using ArcPy

arcgis-10.1arcpyfields-attributestable

I'm looking for a way to get all of the values from a single field in an ArcGIS table. Reasons for doing this might include pasting the values into a text document or SQL where clause.

Since ArcGIS 10.1 does not seem to have a way to do this (like right-click the field > Copy), I would like to see if I could write an ArcPy script to do this for me. The following code will write the values to the Python window if I pass it an explicit tablename and fieldname:

import arcpy
cur = arcpy.SearchCursor("myTableName")
fieldname = "myFieldName"

for row in cur:
    print row.getValue(fieldname)

del row, cur

However, to make this a dynamic tool, I would like to determine a way to identify:

  1. the active table (in the table window), and
  2. the active (highlighted) column/field in that table

at which point I can dynamically change the tablename and fieldname in the code above, based on what is selected.

Any ideas?

Best Answer

So, while not as interactive as what I was originally going for, I re-thought my options and realized I could just create a Python GP tool that allows the user to choose the tablename and fieldname from a standard GP dialog box. I also added a boolean checkbox that would allow the user to either list out each item on a new line, or as a string converted Python list. You will need to set the fieldname parameter to be "Obtained from" the table parameter in the GP tool parameters setup dialog.

Just like any GP tool, it will only display values for the currently selected set of features, if a selection set exists.

import arcpy

tablename = arcpy.GetParameterAsText(0)
fieldname = arcpy.GetParameterAsText(1)
asCSV = arcpy.GetParameterAsText(2)

#Create a search cursor of selected records
cur = arcpy.SearchCursor(tablename)

#loop over selected elements and print the values
if asCSV == "true":
    csv = []
    for row in cur:
        csv.append(row.getValue(fieldname))
    #Print to dialog as a CSV-style Python list (string)
    arcpy.AddMessage("  {0} from {1}: \n  {2}".format(fieldname,tablename, [item.encode('ascii') for item in csv] ))

else:
    arcpy.AddMessage("  {0} from {1}:".format(fieldname,tablename))
    #Print each item on a new line
    for row in cur:
        print row.getValue(fieldname)
        arcpy.AddMessage("  {0}".format(row.getValue(fieldname)))

del row, cur
Related Question