我已经创建了一个嵌套字典调用表中的值,我需要使用该数据更新要素类的属性表。我使用两个硬编码字段作为测试,但我需要弄清楚如何自动获取featFields
的长度,并使用它来指示要更新的每个字段的索引位置。所以,而不是硬编码row[1]
,row[2]
等和'LOCDESC'
和'RIMELEV'
,我会使用一个变量来逐步通过索引位置为每一个。Python嵌套更新游标与嵌套字典。有一个更简单的方法
我正在Python中工作。最终目标是在ArcMap 10.2或10.3中使用的工具箱。
import arcpy
arcpy.env.workspace = r"C:/SARP10/MACP_Tool"
#Define fields to update and the field to use as join field
Table = "Test2.csv"
Input = "Test.gdb/MHs"
csvFields = ['Location_Details', 'Elevation']
featFields = ['LOCDESC', 'RIMELEV']
csvKey = "Manhole_Number"
featKey = "FACILITYID"
csvFields.insert(0, csvKey)
featFields.insert(0, featKey)
print csvFields
#Create dictionary to store values from the update table
UpdateDict = {}
#Iterates through the values in the table and stores them in UpdateDict
with arcpy.da.SearchCursor(Table, csvFields) as cursor:
for row in cursor:
UpdateDict[row[0]] = dict(zip(featFields[1:], row[1:]))
print UpdateDict
MHNum = len(UpdateDict) # gets # of MHs to be updated
MHKeys = UpdateDict.keys() # gets key values, i.e. MH numbers
print "You are updating fields for the following {} manholes: {}".format(MHNum, MHKeys)
#Iterates through feature class attribute table and updates desired attributes
with arcpy.da.UpdateCursor(Input, featFields) as cursor:
i = 0
z = 0
for row in cursor:
i += 1
for f in UpdateDict.keys():
if f == row[0]:
row[1] = UpdateDict.values()[z]['LOCDESC']#uses counter and subdict key to call correct value
row[2] = UpdateDict.values()[z]['RIMELEV']#uses counter and subdict key to call correct value
cursor.updateRow(row)
z +=1 #counter keeps track of rows and provides index location for dictionary
print "Updating {} of {} manholes in this submittal: {}.".format(z, MHNum, f)
else:
pass
print "Updated {} of {} rows.".format(MHNum, i)
print "Script completed."
我试过这样,昨晚一环,但它抛出抛出一个RuntimeError:“值类型与字段类型不兼容”。硬编码版本工作正常,所以我想知道是否有嵌套逻辑的问题。我完全运行你的代码,除了一个变化:我开始与范围内的j(1,len(featFields)-1)排除键'FACILITYID'添加到索引位置0.再次获取该错误...任何人都可以告诉我为什么? –
_value类型的incompatible_error听起来像是试图将一个字符串值放入一个数字字段(即'RIMELEV'可能是一个字符串''3''而不是一个整数'3')。 – Erica
我的本能说同样的事情......但为什么硬编码版本没有错误地工作?循环版本有什么不同?这就是我需要识别和修复的东西,我很难过。 –