Since the field datatypes are static, you can pre-cast pylist
to whatever you need it to be. For example:
pylist= [(1.0, u'10',''), (2.0, 1.0, 2.0), (u'9', '', 2.0)]
cast = [(float(x), str(y), str(z)) for x,y,z in pylist]
#[(1.0, '10', ''), (2.0, '1.0', '2.0'), (9.0, '', '2.0')]
fields =["A", "B", "C"] #fields of arcgis table
#using with means closure in the event of completion/failure
with arcpy.da.InsertCursor(tablename, fields) as row:
for triplet in cast: #Don't need to use indexing
row.insertRow(triplet)
You'll just need to make sure that pylist
actually supports what you are casting to.
Edit: The solution is to use class
, although this isn't the prettiest way to do it. getattr()
is handy here.
class Caster:
def __init__(self, val):
self.val = val
def to_int(self):
return int(self.val)
def to_str(self):
return str(self.val)
def to_float(self):
return float(self.val)
pylist= [(1.0, u'10',''), (2.0, 1.0, 2.0), (u'9', '', 2.0)]
fields =["A", "B", "C"] #fields of arcgis table
#Create list of field types for existing names
ftypes = [f.type for f in arcpy.ListFields(tablename) if f.name in fields]
ftypes = ["DOUBLE", "TEXT", "TEXT"]
#Create dictionary of the form fieldtype:<Caster method name>
fdict = dict([("SHORT", "to_int"), ("LONG", "to_int"), ("TEXT", "to_str"), ("DOUBLE", "to_float")])
types = [fdict[t] for t in ftypes] #List of builtin cast functions as strings
cast = [[getattr(Caster(val), types[i])() for i,val in enumerate(vals)] for vals in pylist]
#using with means closure in the event of completion/failure
with arcpy.da.InsertCursor(tablename, fields) as row:
for triplet in cast: #Don't need to use indexing
row.insertRow(triplet)