Insert cursor to iterate through dictionary

1993
3
10-06-2018 07:32 AM
JacobHorwitz1
New Contributor II

I'm trying to set an arcpy da insert cursor to iterate through a dictionary that adds in the rhino's name. I'm missing a code that would loop through the cursor.

def rhinoTracker(Rhino, X, Y, dictionary):

    # Sets the variable for arcpy.Point
    vertex = arcpy.Point(X, Y)

    # If the Rhino is in the dictionary, points are added.
    if Rhino in dictionary:
        vertexArray = dictionary[Rhino]
        vertexArray.add(vertex)
        #print str(dictionary.values())
        
    # If the Rhino is not in the dictionary, an array created.
    else:
        vertexArray = arcpy.CreateObject("Array")
        vertexArray.add(vertex)
        dictionary[Rhino] = vertexArray
        #print str(dictionary.values())
        

    #for Rhino in dictionary:
        print "This the key {0}".format(Rhino)
        print "These are {0}'s points {1}".format(Rhino, dictionary[Rhino])
        print "{0} has {1} points".format(Rhino, str(len(dictionary[Rhino])))


#--------------------------------------------------------------------------

# Imports the csv and arcpy modules.
import csv
import arcpy

# Sets up the workspace environment and overwrite output.
arcpy.env.workspace = "E:\College\Penn State\GEOG 485\Lesson 4\JHorwitz_Lesson4_Submission\Shapefiles"
arcpy.env.overwriteOutput = True

#--------------------------------------------------------------------------

# Sets a path for the folder containing the shapefile.
Path = "E:\College\Penn State\GEOG 485\Lesson 4\JHorwitz_Lesson4_Submission\Shapefiles"

# Uses the "MysteryState.shp" as the spatial reference.
spatialpath = "E:\College\Penn State\GEOG 485\Lesson 4\JHorwitz_Lesson4_Submission\Shapefiles\MysteryState.shp"

# Sets up the "RhinoObservations.csv" as the csv file.
RhinoObservation = open("E:\College\Penn State\GEOG 485\Lesson 4\JHorwitz_Lesson4_Submission\RhinoObservations.csv", "r")

# Creates the Polyline shapefile as "RhinoTrack.shp" using "MysteryState.shp" as the spatial reference and the folder to store the shapefile.
arcpy.CreateFeatureclass_management(Path, "RhinoTrack.shp", "POLYLINE", "", "DISABLED", "DISABLED", spatialpath)

# Creates a new text field for the Rhino polyline.
arcpy.AddField_management("RhinoTrack.shp", "Name", "TEXT")

# Sets up the file path to "RhinoTrack.shp"
rhinoLine = "E:\College\Penn State\GEOG 485\Lesson 4\JHorwitz_Lesson4_Submission\Shapefiles\RhinoTrack.shp"

# Sets up the spatial reference for the rhinoLine.
spatialRef = arcpy.Describe(rhinoLine).spatialReference

#--------------------------------------------------------------------------

# Sets up a csv reader and will process the header.
csvReader = csv.reader(RhinoObservation, delimiter=",")
header = csvReader.next()
xIndex = header.index("X")
yIndex = header.index("Y")
rhinoIndex = header.index("Rhino")

# Creates the rhinoList dictionary.
rhinoList = {}


# Loop through the lines in the csv file to get the coordinates and rhino name.
for row in csvReader:
    Rhino = row[rhinoIndex]
    X = row[xIndex]
    Y = row[yIndex]
    rhinoTracker(Rhino, X, Y, rhinoList)
    
    with arcpy.da.InsertCursor(rhinoLine, ("SHAPE@")) as cursor:
        for Rhino in cursor:
            polyline = arcpy.Polyline(vertexArray, spatialpath)
            cursor.insertRow((polyline,))
        
    # Updates and fills up the new text field as OpenStreetMap using a "with" loop.
    with arcpy.da.UpdateCursor("RhinoTrack.shp", "Name") as cursor:

        #Uses a "for" loop to insert each row.
        for Name in cursor:
            Name[0] = Rhino
            cursor.updateRow(Name)

Between line 79-82, I need to use the insert cursor to iterate through a dictionary and I'm not sure how.

0 Kudos
3 Replies
JoshuaBixby
MVP Esteemed Contributor

set an arcpy da insert cursor to iterate through a dictionary

As written, it isn't possible to do what you state.  ArcPy cursors, whether old/original or newer/data access, do not operate on Python dictionaries.  Do you want to iterate through a dictionary and use an ArcPy cursor to insert the keys and/or values into a shapefile?

A couple of comments I can make:

  • When working with Windows OS paths in Python, you will want to use raw string formatting or escape all of the backslashes; otherwise, you are bound to run into problems at some point.
    • e.g., instead of "C:\tmp\shapefile.shp", it would be r"C:\tmp\shapefile.shp" or "C:\\tmp\\shapefile.shp"
  • Having a variable name with a Python data structure name in it, but having the data structure being something else is bound to cause confusion.
    • e.g., rhinoList implies the variable refers to a Python list but it really refers to a Python dictionary.
RandyBurton
MVP Regular Contributor

See InsertCursor for some code examples.  I agree with Joshua Bixby‌; you probably want to iterate through a dictionary to insert the keys/values into a shape file or feature.  The flow would go like this:

rhinoDict = {}

# read csv into rhino dictionary
for row in csvReader:
    # code to build dictionary

# open an insert cursor
cursor = arcpy.da.InsertCursor(feature, fields)

# loop through the dictionary
for rhino in rhinoDict.iteritems():
    # retrieve data from the dictionary
    # organize and insert it into feature/shapefile
    cursor.insertRow((data))

# delete cursor object
del cursor

# other steps to finish

Be sure to include some print statements for debugging.   You will probably want to print your rhino dictionary to see that it is in the expected format, that you are reading the correct values from it, etc.

DanPatterson_Retired
MVP Esteemed Contributor