1

So I have the table like this:

City Distance NearFeature Comments
A    90.5     131025    
A    0        781446    
B    15.5     131057    
B    42.2     140521    
C    21.7     784116    
C    0        131025    

Distance field contains distance value from the City to the NearFeature. Zero in the Distance field means that the City is completely inside the NearFeature.

What I want to accomplish is to populate the Comments field with the value from the NearFeature for Cities which are inside any NearFeature…. Like this:

City Distance NearFeature Comments
A    90.5     131025      City within 781446
A    0        781446      City within 781446
B    15.5     131057    
B    42.2     140521    
C    21.7     784116      City within 131025
C    0        131025      City within 131025

For B the Comments field is empty because it is outside any NearFeature.

Here is what I’ve done so far. This code updates the table, but only for rows which have 0 in the Distance field. What do I need to change to make it work in the way I need?

cities = arcpy.da.SearchCursor(Path+"\\city.shp", "City")
citynames = []

with cities as rows:
    for row in rows:
        name = row[0]
        if name not in citynames:
            citynames.append(name)
del row, rows

fields = ["City", "Distance", "NearFeature", "Comments"]
with arcpy.da.UpdateCursor(Path+"\\city.shp", fields) as rows: 
    for row in rows:
        for i in citynames:
            if str(row[0]) in i and row[1] == 0:
                row[3] = 'City within '+ row[2]
                rows.updateRow(row)
del row, rows
4

This can be solved with use of a dictionary object. Dictionaries let you associate a key value with another value. In the code below, I use your first cursor to associate the City value with the NearFeature value, if the Distance value is 0. I then use your second cursor to update the Comments field, if the value in the City field occurs in the dictionary.

cities = arcpy.da.SearchCursor(Path+"\\city.shp", ["City", "Distance", "NearFeature"])
#Create empty dictionary
di = {}

with cities as rows:
    for row in rows:
        #Check if Distance is 0
        if row[1] == 0:
            #Add key as City and value as NearFeature
            di[row[0]] = row[2]
del row, rows

fields = ["City", "Comments"]
with arcpy.da.UpdateCursor(Path+"\\city.shp", fields) as rows: 
    for row in rows:
        #Check if City value is in dictionary
        if row[0] in di:
            row[1] = 'City within ' + str (di[row[0]])
            rows.updateRow(row)

del row, rows

I hope this helps!

  • It works! Thanks a lot Emil! I learn bit by bit every day... – Olga K. Dec 12 '14 at 17:21
  • Excellent. Keep on pythoning! – Emil Brundage Dec 12 '14 at 17:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.