Help with fieldmappings in SpatialJoin in python

Discussion created by jphiloon on Nov 22, 2013
I have a situation where the same field name, "FIPS", is in both the target class and the join class.  I want the output FC to contain the field from the join class.  What happens is that the FIPS field from the target class always ends up in the output, even though the fieldmappings object seems correct in specifying the field should come from the join class.  Note that any fields from the join class that are not present in the target show up in the output correctly.

I must be doing something stupid.  Below is an excerpt from my code - what's wrong?

def createFieldMap(fc_in, inFldName, outFldName):
        field_map = arcpy.FieldMap()
        field_map.addInputField(fc_in, inFldName)
        field = field_map.outputField = outFldName
        field_map.outputField = field
        return field_map
        raise Exception, "Error: cannot map field %s from %s" % (infFldName, fc_in)

def deleteFieldMaps(fieldmappings, fieldNames):
    fieldNames = fieldNames.replace(',',' ')    # comma or space delimiter
    names = fieldNames.split()
    for name in names:
        index = fieldmappings.findFieldMapIndex(name)
        if index >= 0:
fieldmappings = arcpy.FieldMappings()
# other setup ...#
deleteFieldMaps(fieldmappings, "Join_Count,TARGET_FID,FIPS")
fieldmappings.addFieldMap(createFieldMap(joinFeatures, "FIPS", "FIPS")) # doesn't work - output has target value of <null>
fieldmappings.addFieldMap(createFieldMap(joinFeatures, "JOIN_FLD", "JOIN_FLD")) # works fine
arcpy.SpatialJoin_analysis(targetFeatures, joinFeatures, outFC, "JOIN_ONE_TO_ONE", "KEEP_ALL", fieldmappings, "WITHIN", "", "")