KeyError: '#' When Calculating Geometry in Arcpy

Jump to solution
02-25-2021 03:23 PM
New Contributor III

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 == "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."), 'Acres', area_unit="ACRES")  # Calculate the area
    arcpy.AddMessage("Area calculated.")

Any help would be appreciated. 

Tags (2)
1 Solution

Accepted Solutions
Esri Contributor

Replace, 'Acres', area_unit="ACRES")

With, [["Acres", "AREA"]], area_unit ="ACRES")

View solution in original post

4 Replies
MVP Esteemed 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...
Esri Contributor

Replace, 'Acres', area_unit="ACRES")

With, [["Acres", "AREA"]], area_unit ="ACRES")

MVP Frequent Contributor

What Dan and Davin said.

Plus, you can just do this:


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

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


Have a great day!
New Contributor III

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

0 Kudos