KeyError: '#' When Calculating Geometry in Arcpy

381
4
Jump to solution
02-25-2021 03:23 PM
JamesWilcox1970
New Contributor II

As part of a larger script, I have code that checks to see if a particular field exists. If not, it creates it and calculate its area. The script works just fine until it goes to calculate the area of the newly created field, where it gives me KeyError: '#'. Is this error because the field was just created? If so, how do I work around it?

I am running Python 3.6 with PyCharm.

Here is the code I am having issues with--"projArea" is the project area feature class.

# Test to see if there is an "Acres" field in the Project Area FC.
projFields = arcpy.ListFields(projArea)  # List of fields in project area fc
x = False  # Default condition is that the field doesn't exist
for f in projFields:
    if f.name == "Acres":  # If there is a field named "Acres"
        x = True
if x is not True:  # If none of the fields are named "Acres"
    arcpy.AddMessage("{} does not have an Acres field. Creating field.".format(projArea))
    arcpy.AddField_management(projArea, 'Acres', 'DOUBLE')  # Create the field
    arcpy.AddMessage("Calculating area.")
    arcpy.management.CalculateGeometryAttributes(projArea, 'Acres', area_unit="ACRES")  # Calculate the area
    arcpy.AddMessage("Area calculated.")

Any help would be appreciated. 

Tags (2)
0 Kudos
1 Solution

Accepted Solutions
DavinWalker2
Esri Contributor

Replace 

arcpy.management.CalculateGeometryAttributes(projArea, 'Acres', area_unit="ACRES")

With arcpy.management.CalculateGeometryAttributes(projArea, [["Acres", "AREA"]], area_unit ="ACRES")

View solution in original post

4 Replies
DanPatterson
MVP Notable Contributor

["Left", "EXTENT_MIN_X"]

in your case

[projArea, 'AREA']

Calculate Geometry Attributes (Data Management)—ArcGIS Pro | Documentation

a list is required for the first parameter, the field name and the property


... sort of retired...
DavinWalker2
Esri Contributor

Replace 

arcpy.management.CalculateGeometryAttributes(projArea, 'Acres', area_unit="ACRES")

With arcpy.management.CalculateGeometryAttributes(projArea, [["Acres", "AREA"]], area_unit ="ACRES")

View solution in original post

JohannesLindner
Occasional Contributor II

What Dan and Davin said.

Plus, you can just do this:

 

#projFields = arcpy.ListFields(projArea)
#x = False
#for f in projFields:
#    if f.name == "Acres":
#        x = True

projFieldNames = [f.name for f in arcpy.ListFields(projArea)]  # extract field names
x = "Acres" in projFieldNames  # Test if field "Acres exists

 


Have a great day!
Johannes
JamesWilcox1970
New Contributor II

That worked! I *knew* it was something that was staring me in the face. Thank you, all!

0 Kudos