I have two features classes that should have the exact same fields. There are over 500 fields, I am looking for a code that will compare the fields and identify if there are fields in either feature class that are not in the other.
I found this solution, Comparing multiple field values of two feature classes using ArcPy? but was hoping to not have to type out each field.
1 Answer
List the fields using set comprehension, compare the sets:
import arcpy
fc1 = r'C:\GIS\data\Bakgrundskartor_LMV\Oversiktskartan.gdb\ak_riks'
fc2 = r'C:\GIS\data\Bakgrundskartor_LMV\Oversiktskartan.gdb\ak_riks_1'
fields1 = {f.name for f in arcpy.ListFields(fc1)}
fields2 = {f.name for f in arcpy.ListFields(fc2)}
print 'Fields in common: ', fields1.intersection(fields2)
if not fields1==fields2: #If they are not the same
print 'only exist in fc1, and not in fc2: ', fields1.difference(fields2)
print 'only exist in fc2, and not in fc1: ', fields2.difference(fields1)
-
I see you are using set() methods but is fields1 and fields2 not a dictionary because they are {}?– HornbyddJan 14, 2022 at 15:58
-
1No sets also use {}. I guess python know it is a set if there are no key:values– BERAJan 14, 2022 at 15:59
-
1Ah OK! I've only ever created a set like
mySet = set()
never knew it could be {}, I find that confusing! But a good answer showing the power of sets.– HornbyddJan 14, 2022 at 16:01 -
1Nice, clean approach to check if the field names and list sizes are the same. The OP is also looking to check if the fields are the same type. How about integrating a check using
f.type
?– Aaron ♦Jan 14, 2022 at 17:15
ListFields
and comparing the lists? More details: pro.arcgis.com/en/pro-app/latest/arcpy/functions/listfields.htm