Thursday 30 April 2015

arcpy - Selecting features by attribute if in Python list?


I am trying to complete a select by attribute in Python but based on the query of whether an attribute is present in a list.


Such a query at its simplest should be something like this:


qry = " \"OBJECTID\" in oid_list"
arcpy.SelectLayersByAttribute_management(inft, "NEW_SELECTION", qry)

but that approach returns an invalid expression error.


In the past, I've had to use more complicated sytax for this type of query, such as:


sqlQuery2 = "nid in (" + ','.join(["'"+x+"'" for x in delta_list]) +")"


but an adaptation of this snippet doesn't seem to work for me either, ie.:


 "OBJECTID_1 in (" + ','.join(["'"+str(x)+"'" for x in oid_list]) +")"

What am I missing here?



Answer



Your original query could have been modified for a list of integers:


'"OBJECTID_1" IN ' + str(tuple(oid_list))

so if oid_list = [7, 9, 4, 8], then the result is:


"OBJECTID_1" IN (7, 9, 4, 8)


Be aware that this "trick" works if oid_list always has two or more items, since other valid tuples, such as () or (7,), will result with a SQL syntax error.


A more generic expression that would also handle zero or one oid_list items would be:


'"OBJECTID_1" IN ({0})'.format(', '.join(map(str, oid_list)) or 'NULL')

No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...