Search code examples
pythondictionarypolylinearcpyarcmap

How can I remove items from a dictionary while iterating throught the dicionary given a starting dictionary key in the loop


I am trying to draw polylines from points I have in a dictionary as {OID:PointGeometry,,,}, I am trying to start at a given OID and find the nearest point stored in another dictionary. The second dictionary is exactly the same as the first only it is missing the first point being searched from in the first dictionary. While iterating through the dict I want to delete the points that have been drawn through from the dictionary so that lines don't overlap. 1 dictionary has 141 items the other 140 items. For some reason no points are being deleted and the loop only seems to iterate once.

for k in pointDict.keys():
    if k==startOid:
        distances={}
        shape=pointDict[k]
        X=shape.centroid.X
        Y=shape.centroid.Y
        Z=shape.centroid.Z
        for k2 in pointDict2.keys():
            shape2=pointDict2[k2]
            X2=shape2.centroid.X
            Y2=shape2.centroid.Y
            Z2=shape2.centroid.Z
            dist=sqrt((X-X2)**2+(Y-Y2)**2)
            distances[k2]=round(dist,4)

        minSearch=(min(distances.items(), key=lambda x:x[1]))
        print minSearch,minSearch[0]
        global startOid
        startOid=minSearch[0]
        del pointDict[k]
        del pointDict2[k2]

Solution

  • You don't even need pointDict2. You could do the following:

    import math
    
    startOid = ...
    # While there are more elements to draw
    while len(pointDict) > 1:
        shape = pointDict.pop(startOid)
        X = shape.centroid.X
        Y = shape.centroid.Y
        Z = shape.centroid.Z
        nextOid = None
        minSquaredDist = math.inf
        for otherOid, otherShape in pointDict.items():
            otherX = otherShape.centroid.X
            otherY = otherShape.centroid.Y
            otherX = otherShape.centroid.Z
            squaredDist = (X - otherX) ** 2 + (Y - otherY) ** 2  + (Z - otherZ) ** 2
            if squaredDist < minSquaredDist:
                minSquaredDist = squaredDist
                nextOid = otherOid
        minDist = math.sqrt(minSquaredDist)
        print minDist, nextOid
        startOid = nextOid