Getting arcpy.da rows back as dictionaries

Though arcpy.da‘s cursors return rows as lists, you can easily transform these on-the-fly with just a little code on your part:

Or if you’d like to be able to use a syntax similar to the old arcpy cursors and do row.COLUMN_NAME to fetch a value, you could use namedtuples:

And then to get a little more sophisticated, what about an update cursor that lets you use dictionaries? Note that in this example the row will ALWAYS update without any intervention on your part once you go to the next one, so be careful:

All the pieces are there in the Python standard library and arcpy.da to customize how you get your data in and out. The reason that arcpy.da returns lists and tuples is because they act as a sort of lowest-common-denominator of data structures, and in large datasets things like a dictionary key lookup benchmarks much, much slower than a simple list item assignment.

About these ads

5 thoughts on “Getting arcpy.da rows back as dictionaries

  1. This are very good ideas, thanks. Question: In the 3rd example, in the context manager, shouldn’t it be “with arcpy.da.UpdateCursor. . .” ?

  2. Is there a typo in your examples? In the first example you call “print sc['CITY_NAME']” Shouldn’t that be “print row['CITY_NAME']” I could not get it to work with your code but it did work the other way. Either way thanks for the post its a great direction to go.

    • Hi Gus,
      Thanks for pointing this out. You are correct, it should be: print row['CITY_NAME'].

      ~ ArcGISTeamPython

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s