Search code examples
pythonlistcsvarcgis

Correct method to iterate through an array and apply string as an attribute name?


I have a .csv containing with a large amount of columns and rows. I use python to read the csv and create a table/feature class in ArcGIS and populate the table with the rows from then .csv. I am looking for the best way/shorthand method of the following:

I have a list representing the first row of the .csv "csv_headers".

A short example CSV below shows the list would be:

csv_headings = ['Key', 'X', 'Y', 'Value1', 'Value2'...]

Key        X      Y       Value1    Value2    ...
2221    192934  875767     96.4      95.4
2222    194459  834763     96.3      99.9
2223    193934  905606     90.6      95.1
2224    191974  855100     91.0      95.2
...

Currently the following is used to populate the table/feature class in ArcGIS:

with open("C:\\path_to_csv.csv", 'rb') as f:
  reader = csv.DictReader(f)
  for row in reader:
    # Create the feature
    feature = cursor.newRow()

    # Add the point geometry to the feature
    vertex = arcpy.CreateObject("Point")
    vertex.X = row['X']
    vertex.Y = row['Y']
    feature.shape = vertex

    # Add attributes
    feature.Key = row['Key']
    feature.X = row['X']
    feature.Y = row['Y']
    feature.Value1 = row['Value1']
    feature.Value2 = row['Value2']

My full dataset has 43 columns, and currently is all written in manually as "feature.ValueX = row['ValueX'] for 43 lines, which I am looking to shorten.

Essentially I'd like to iterate through "csv_headers" as x and apply x as both the attribute name and the row title, hypothetically:

    # Add attributes

    for x in csv_headers:
      feature.x = row[x]

However this will not work, just wondering what the correct way of thinking around this might be? Any help would be appreciated.


Solution

  • The short answer is:

    for attr in csv_headings:
        setattr(feature, attr, row[attr])
    

    and the setattr docs is here.