1

I'm new in programming and I'm struggling with my code. I have a dictionnary of districts and communities for each, like this:

MyDict = defaultdict(<type 'set'>, {u'DISTRICT': set([u'community1', u'community2']),
u'DISTRICT2': set([u'community3', u'community6'])})

Now I want to add the list of values in a shapefile of districts, in the row corresponding to the right district: so the field in this shapefile called 'District' has to be the same as the key of my dictionary if I understood well. Expected result in shp:

<District>   |   <Communities>              |
DISTRICT     |   community1, community2     |
DISTRCIT2    |   community3, community6     |

My code isn't working, I get no error message but nothing written in the expected field:

Communities = ['Communities']           #field to be written with values
District = ['District']                 # field with district in the shp

# Update in the communities field of the Districts shapefile
with arcpy.da.UpdateCursor(MyDistrictShapefile, Communities) as cursor1:
for newRow in cursor1:

  # Define a loop pour all the district name in the shapefile
  districtsLoop = [row[0] for row in arcpy.da.SearchCursor(MyDistrictShapefile, District)]

  # Looking for the same district as the key and update the communities field
  if str(districtsLoop[0]) == str(myDict.keys()) :
     newRow[0] = myDict[str(districtsLoop[0])]
  cursor1.updateRow(newRow) 

Anyone has an idea of how I can solve my problem? It's my first code and I don't see how to fix this.

  • try to indentent: for newRow in cursor1 and the following lines – BERA Apr 24 '17 at 8:04
2

I dont understand all of your code but i'll give some parts of it a try: Why do you need a searchcursor inside the updatecursor when you already have created a Dictionary?

You should also need both fields (district and Community) in the updatecursor. District for use in the Dictionary and Community which you will calculate.

with arcpy.da.UpdateCursor(MyDistrictShapefile, ['District','Communities']) as cursor1:
    for newRow in cursor1:
        try:
            row[1]=MyDict[row[0]]
            cursor1.updateRow(newRow)
        else:
            pass

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.