Arcpy Python Cursor – How to Search Cursor and Return Field Name If All Rows Contain a Value

arcpycursorpython

I'm trying to print the field name to a list if all rows in that field are not NULL. Here is the logic I have so far.

fiberCable = r'Orlando\Orlando_FIM_prep\FIBERCABLE'
list = []
with arcpy.da.SearchCursor(fiberCable, "inventory_status_code") as cursor:
     for row in cursor:
         if row[0] is not None:
             list.append(str(row[0]))

enter image description here

Using the logic on the table above it prints out this list:

['Preliminary Designed', 'DesignComplete', 'DesignComplete', 'DesignComplete', 'DesignComplete']

How do I get the search cursor to look at the row of values in the field and if there is a value present in all rows, print the field name, which in this case would be 'inventory_status_code'.

The outcome I would be looking for here is:
['inventory_status_code']

Best Answer

The most efficient way to do it (i.e., not reading every single row in the table) is to do this...see the comments for explanation:

import arcpy
fiberCable = r'Orlando\Orlando_FIM_prep\FIBERCABLE'
field = "inventory_status_code"
# Go ahead and put the field name into the output list
output_fields = [field]
# Compose a where clause to limit the cursor to iterate over records where the field is null
where_clause = '{} IS NULL'.format(field)
with arcpy.da.SearchCursor(fiberCable, field, where_clause) as cursor:
     # If any records are null, remove the field name from the output list and then break out of the loop.
     for row in cursor:
         output_fields.remove(field)
         break

Assuming that you want to do this for multiple fields:

import arcpy
fiberCable = r'Orlando\Orlando_FIM_prep\FIBERCABLE'
fields = ["inventory_status_code", 'another_field_name']
output_fields = list()
for field in fields:
    output_fields.append(field)
    where_clause = '{} IS NULL'.format(field)
    with arcpy.da.SearchCursor(fiberCable, field, where_clause) as cursor:
         for row in cursor:
             output_fields.remove(field)
             break

By the way, never ever ever use a python keyword of any kind as a variable name (e.g., list)

Related Question