I am trying to use dictionary to help update a field. I have the following but I am getting an error.
Basically, if field "Type" has PVT, I want it to update with "Private" and if Pub, I want it to update with "Public".
the filed doesn't get updated. I am assuming that dict is wrong?
import arcpy
fc = r"C:\Temp\test.gdb\Testb"
search_feats ={f[0]:(f[:1] for f in arcpy.da.SearchCursor(fc,"Type")}
print(search_feats) #'OID@', 'Type'
place_dict = {"PVT": "Private",
"Pub": "Public"
}
with arcpy.da.UpdateCursor(fc,"Type") as upd_cur:
for upd_row in upd_cur:
if upd_row[0] in place_dict:
upd_row[0] = place_dict.get(search_feats[upd_row[0]], upd_row[0])
upd_cur.updateRow(upd_row)
Solved! Go to Solution.
I'm not really sure what the point of search_feats is, to be honest.
In any case, I'd get rid of search_feats on line 16; you want to be checking place_dict, and since you're using get, you don't need to write place_dict[upd_row[0]].
import arcpy
fc = r"C:\Temp\test.gdb\Testb"
search_feats ={f[0]:(f[:1] for f in arcpy.da.SearchCursor(fc,"Type")}
print(search_feats) #'OID@', 'Type'
place_dict = {"PVT": "Private",
"Pub": "Public"
}
with arcpy.da.UpdateCursor(fc,"Type") as upd_cur:
for upd_row in upd_cur:
if upd_row[0] in place_dict:
upd_row[0] = place_dict.get(upd_row[0], upd_row[0])
upd_cur.updateRow(upd_row)
I'm not really sure what the point of search_feats is, to be honest.
In any case, I'd get rid of search_feats on line 16; you want to be checking place_dict, and since you're using get, you don't need to write place_dict[upd_row[0]].
import arcpy
fc = r"C:\Temp\test.gdb\Testb"
search_feats ={f[0]:(f[:1] for f in arcpy.da.SearchCursor(fc,"Type")}
print(search_feats) #'OID@', 'Type'
place_dict = {"PVT": "Private",
"Pub": "Public"
}
with arcpy.da.UpdateCursor(fc,"Type") as upd_cur:
for upd_row in upd_cur:
if upd_row[0] in place_dict:
upd_row[0] = place_dict.get(upd_row[0], upd_row[0])
upd_cur.updateRow(upd_row)
I'm not sure what purpose "search_feats" serves, but something simpler like this should work fine:
import arcpy
fc = r"C:\Temp\test.gdb\Testb"
place_dict = {"PVT": "Private", "Pub": "Public" }
with arcpy.da.UpdateCursor(fc,"Type") as upd_cur:
for upd_row in upd_cur:
# replace the string with the matching value or leave it alone
upd_row[0] = place_dict.get(upd_row[0], upd_row[0])
upd_cur.updateRow(upd_row)
@AlfredBaldenweck jinx 😀
What is the entire purpose of search_feats? why this?
upd_row[0] = place_dict.get(search_feats[upd_row[0]], upd_row[0])
your indentation on updateRow is also a level too deep.
with arcpy.da.UpdateCursor(fc,"Type") as cursor:
for row in cursor:
if row[0] in place_dict:
row[0] = place_dict[row[0]]
cursor.updateRow(row)
That was the issue, for some reason I thought I need the "search_feats" on line 16.