How to use field name instead or numeric index to find value in row,cursor

10-05-2017 09:37 AM
Occasional Contributor III

Hello everyone,

I am looking for a way to compare fields from two rows from two SearchCursor but I would like to use a filed name instead of a numeric index

instead of  if rowYesterday[1] != rowToday[1] ]:   

is there a way to check  for

if rowYesterday[ 'CODE'] != rowToday['CODE'] ]:


This is a simplified version of my source code:

with arcpy.da.SearchCursor(WASDWSCORDINANCELETTER_Psde3, fieldnames, whereClause) as srcYesterday:
      for rowYesterday in srcYesterday:

                     if rowYesterday[1] != rowToday[1] ]:

                        // Do somenting

2 Replies
Regular Contributor

Heya Jose,

The help docs for da.Search cursor says:

Returns an iterator of tuples. The order of values in the tuple matches the order of fields specified by the field_namesargument.

That means that in your case, rowYesterday is a tuple with whatever number of values is in your fieldnames tuple or list. So, unfortunately this won't work:

if rowYesterday[ 'CODE'] != rowToday['CODE'] ]:

because rowYesterday is a tuple with no idea what 'CODE' means.

Now for the good news. You can look up the 'CODE' value in your rowYesterday tuple by getting CODE's index value from your fieldnames list and then using that to access the value from your rowYesterday tuple. To do that, the syntax would be:


The .index('value') method returns the index (position) value of that string in your list of field names. So, it's not exactly what you were going for but should produce the desired result.


MVP Esteemed Contributor

If you really want to work with search cursor rows as dictionaries instead of tuples, you can insert a line to create a dictionary with each iteration:

with arcpy.da.SearchCursor(fc, flds) as cur:
    for row in cur:
        row = {k:v for k,v in zip(cur.fields,row)}
        # or row = dict(zip(cur.fields,row))

There are more ideas in a blog post on the old ArcPy Cafe site:  Getting arcpy.da rows back as dictionaries | ArcPy Café .

Dictionary comprehensions are quite quick, but there is still overhead for creating a dictionary with each iteration.  How much of an impact that overhead has on your script depends on what else you are doing within each iteration.

It would be quite handy if ArcPy cursors were implemented as ordered dictionaries, or at least supported them.  I bring the issue up from time to time with product management, but it just seems the community and customers as a whole aren't calling for it.