Hi,
I was wondering if there is a way to write a script where a list of fields can be self indexing for the search or update cursor?
The reason for this is because I am trying to set up a script tool in such a manner that regardless of the order of the fields, the script will be intelligent enough to identify those fields and then be able search through the attributes with those fields without the need for manually indexing. I have a list of important attributes as well as the fields in which those values reside, but I would write the script to self index and search for those specific values.
I figured enumerating the list of fields and creating a dictionary for the enumerated values is a start, but figuring out how to go from there is a bit tricky for me at the moment. So I wanted to reach out and see if anyone has ever attempted this, and if so, how did you write it.
Solved! Go to Solution.
Here is a little code that is creating the field list, then using the list to get the index for the cursor.
updatedflds = [f.name for f in arcpy.ListFields(updatedAddress)]
with arcpy.da.UpdateCursor(adr, updatedflds, sql) as uCur:
for row in uCur:
# set the row values
for fld in updatedflds:
row[updatedflds.index(fld)] = fldvalue
I have an example for using a dictionary if you want to see that one as well.
Here is a little code that is creating the field list, then using the list to get the index for the cursor.
updatedflds = [f.name for f in arcpy.ListFields(updatedAddress)]
with arcpy.da.UpdateCursor(adr, updatedflds, sql) as uCur:
for row in uCur:
# set the row values
for fld in updatedflds:
row[updatedflds.index(fld)] = fldvalue
I have an example for using a dictionary if you want to see that one as well.
Thanks Jeff for sending me this sample code. This is a lot closer to what I was looking for. I completely forgot that I could have used the ().index method to auto-identify the rows without the needing to specify the index manually.
What about this spiffy trick where you can reference the values of a row by field name using a dictionary?
def rows_as_dicts(cursor):
colnames = cursor.fields
for row in cursor:
yield dict(zip(colnames, row))
with arcpy.da.SearchCursor(r'c:\data\world.gdb\world_cities', '*') as sc:
for row in rows_as_dicts(sc):
print row['CITY_NAME']
Getting arcpy.da rows back as dictionaries | ArcPy Café (wordpress.com)
Thanks BlakeTerhune for the help. I haven't seen this method before nor did I even know about it. I will definitely have to give this a try when I get around to it. This would be extremely helpful for making general script tools rather than having to script something specific all the time.