I try to be a little more explicit when using dictionaries as update sources, and following the turbo charging approach Randy Burton mentions above, just yesterday I was working on this def():
import arcpy, decimal
decimal.getcontext().prec=3
from decimal import Decimal
def updateField():
outSDE = r'I:\GIS\arcsde\SuperUser\slcogis\gdb_AG\gdb_AG@slcogisTEST.sde'
targetFC = r'I:\GIS\arcsde\SuperUser\slcogis\gdb_AG\gdb_AG@slcogisTEST.sde\SLCOGIS.GDB_AG.ClientsDeliveries_2019'
targetFields = ['Zipcode','ClientCount','PercentPopServed']
popSrcTable = r'I:\GIS\ArcSDE\SuperUser\slcogis\gdb_AG\gdb_AG@slcogisTEST.sde\SLCOGIS.GDB_AG.Over60Population_2018'
popSrcFields = ['ID', 'TotalOVer60']
edit = arcpy.da.Editor(outSDE)
edit.startEditing(False, False)
edit.startOperation()
popDict = {r[0]:(r[1]) for r in arcpy.da.SearchCursor(popSrcTable,popSrcFields)}
try:
with arcpy.da.UpdateCursor(targetFC,targetFields) as updateCursor:
for updateRow in updateCursor:
keyValue = updateRow[0]
if keyValue == None:
pass
elif keyValue in popDict:
client = (updateRow[1])
pop = popDict.get(keyValue,[0])
newValue = Decimal(client)/Decimal(pop)*100
updateRow[2] = newValue
updateCursor.updateRow(updateRow)
print('Success: mergeClientToDelivery updated fields in deliveries table in memory')
edit.stopOperation()
edit.stopEditing(True)
except Exception as err:
print('Error: mergeClientToDelivery could not update deliveries table in memory')
print(err)
I have a table of population data referenced as popSrcTable that has a Zipcode field (ID) and the Population of that zipcode (TotalOVer60) and I need to ratio that population value to the number of Clients served (ClientCount) to get a percentage (PercentPopServed) updated in the target feature class.
First step is to create the dictionary of the population data in the form of
{'84009': 2818,'84006': 145,'84084': 4788,'84113': 14.....}
Where the keys values are zipcode, and the associated values are the population. Line 30 is where things get interesting: there it checks for the presence of the zipcode in my target (updateRow[0]). Line 31 gets the number of clients((updateRow[1]). Line 32 is where I 'get' the value of the population for the given zipcode; that's the linch pin when using dictionary. Finally I do a little math and update...
In my case the dictionary is simple: 1 key, 1 value, but you could have multiple values to a single key and update multiple fields if you need to.
That should just about do it....