I have 1 csv with municipalities and their corresponding zip codes and a GDB of houses which contain address, municipality but no zip codes
Objective: add the zip codes to the GDB table
import csv
import arcpy
import arcgisscripting
arcpy.env.overwriteOutput = True
gp = arcgisscripting.create()
file = "path\\munzip.csv"
houses = "path\\geocoding.gdb\\houses"
csvfile = gp.SearchCursor(file) #personally prefer using the object search cursor than arcpy.da
munzip = {}
for x in csvfile:
mun = x.MUN.split()
zip = "0"+str(x.ZIP)
mun = str(mun[0])
munzip[mun] = zip
with arcpy.da.UpdateCursor(houses, ("City","ZIP")) as cur:
for row in cur:
for k,v in munzip.items():
if k == str(row[0]):
row[1]=v
cur.updateRow(row)
1 Answer 1
You need to load all your municipalities and zip codes from your CSV into a dictionary, and then in an update cursor loop through your GDB table, look up each municipality in the dictionary and write the corresponding dictionary zip value into the ZIP column of your GDB table.
This assumes columns in your CSV called "City" and "ZIP".
import arcpy
arcpy.env.overwriteOutput = True
file = r"path\\munzip.csv"
houses = r"path\\geocoding.gdb\\houses"
zipDict = {}
with arcpy.da.SearchCursor(file, ['City', 'ZIP']) as cursor:
for row in cursor:
zipDict[row[0]] = row[1]
with arcpy.da.UpdateCursor(houses, ['City', 'ZIP']) as cursor:
for row in cursor:
if row[0] in zipDict:
row[1] = zipDict[row[0]]
cursor.updateRow(row)
-
2+1. For fun, you can use dict comprehensions with cursors for a handy 1 liner:
zipDict = {row[0] : row[1] for row in arcpy.da.SearchCursor(file, ['City', 'ZIP'])}
Granted, you'll probably have better luck with csv files if you use DictReader.Paul– Paul2016年05月11日 23:33:34 +00:00Commented May 11, 2016 at 23:33 -
1list comprehension is clean and efficient but i honestly prefer to write it all out, makes it easier to read even if it takes up more lines of code. although as i improve i will probably start to use it moreziggy– ziggy2016年05月11日 23:39:26 +00:00Commented May 11, 2016 at 23:39
-
I'm with ziggy on that one as well, I also prefer it all written out just due to the fact that I find it easier to read through later2016年05月11日 23:40:27 +00:00Commented May 11, 2016 at 23:40
-
Or if you want to get real fancy along the lines of what @Paul did, you can do this
zipDict = dict(r for r in arcpy.da.SearchCursor(file, ['City', 'ZIP']))
.crmackey– crmackey2016年05月12日 00:34:25 +00:00Commented May 12, 2016 at 0:34
cur.updateRow(v)
you're trying to update a row that it's not looking at.