python build dictionary for use in table join code example

Example: python build dictionary for use in table join

from time import strftime  
  
print "Start script: " + strftime("%Y-%m-%d %H:%M:%S")  
  
import arcpy  
  
sourceFC = r"C:\Path\SourceFeatureClass"  
  
sourceFieldsList = ["JoinField", "ValueField"]  
  
# Use list comprehension to build a dictionary from a da SearchCursor  
valueDict = {r[0]:(r[1:]) for r in arcpy.da.SearchCursor(sourceFC, sourceFieldsList)}  
  
updateFC = r"C:\Path\UpdateFeatureClass"  
  
updateFieldsList = ["JoinField", "ValueField"]  
  
with arcpy.da.UpdateCursor(updateFC, updateFieldsList) as updateRows:  
    for updateRow in updateRows:  
        # store the Join value of the row being updated in a keyValue variable  
        keyValue = updateRow[0]  
         # verify that the keyValue is in the Dictionary  
        if keyValue in valueDict:  
             # transfer the value stored under the keyValue from the dictionary to the updated field.  
            updateRow[1] = valueDict[keyValue][0]  
            updateRows.updateRow(updateRow)  
  
del valueDict  
  
print "Finished script: " + strftime("%Y-%m-%d %H:%M:%S")

Tags:

Misc Example