[GIS] Using UpdateCursor based on current selection of features

arcpycursorupdate

What I want to do is to manually select two features with the mouse (e.g. point or polygon), each in separate geodatabases to then copy the attributes values from one to the other (for only these two selected objects).

So far I have only managed to copy all attributes from one to the other. I am stuck at how to make update cursor run only on selected objects

I am trying to use something like this to get the selected objects, but this selects the entire layer:

mxd = arcpy.mapping.MapDocument("CURRENT")
layers = arcpy.mapping.ListLayers(mxd)
sel_layers=[str(i.name) for i in layers if arcpy.Describe(i.name).fidSet]

And my update cursor is this:

fc_search = r'C:\PythonFolder\Othergeodatabas.gdb\Polyline'
fc_destination = r'C:\PythonFolder\LKpolygon.gdb\Avloppsbrunn'

with arcpy.da.SearchCursor(fc_search,["DIM","MATERIAL"]) as search_cur:
    for search_row in search_cur:
        with arcpy.da.UpdateCursor(fc_destination,["Tillkomst_plan","Notering"]) as upd_cur:
            for upd_row in upd_cur:
                    upd_row[0] = search_cur[0]
                    upd_row[1] = search_cur[1]
                    upd_cur.updateRow(upd_row)

This code works, but it applies changes to attributes for the entire layer, while I would like to only change attribute values for selected objects.

Best Answer

A selection can only be made on a layer (not a feature class) and if you pass a layer to the cursors only selected rows will be proccessed. You are passing the feature classes to the cursors and that is why all rows are proccessed.

So both fc_search and fc_destination needs to be layers, for example from your sel_layers list, or created with MakeFeatureLayer, or if you are using the python window the layer names as you see them in table of contents (probably "Polyline" or "Avloppsbrunn").

You can also use a feature class as input and use the where_clause parameter of the cursors:

An optional expression that limits the records returned

Related Question