I am having trouble selecting counties that have single quotes and/or periods in their name with python that are stored in a dictionary. The below code I have works on county records with no special characters but does not with the special character counties. Any advice/suggestions?
import arcpy
fc = "Maryland_County_Boundaries"
CountyDict = {
"Allegany": "Allegany",
"Anne Arundel": "Anne Arundel",
"Baltimore": "Baltimore",
"Calvert": "Calvert",
"Caroline": "Caroline",
"Carroll": "Carroll",
"Cecil": "Cecil",
"Charles": "Charles",
"Dorchester": "Dorchester",
"Frederick": "Frederick",
"Garrett": "Garrett",
"Harford": "Harford",
"Howard": "Howard",
"Kent": "Kent",
"Montgomery": "Montgomery",
"Prince George\'s": "Prince George\"s",
"Queen Anne\'s": "Queen Anne\"s",
"St. Mary\'s": "St. Mary\"s",
"Somerset": "Somerset",
"Talbot": "Talbot",
"Washington": "Washington",
"Wicomico": "Wicomico",
"Worcester": "Worcester"
}
for k,v in CountyDict.items():
if k == "Prince George's":
qry = '"' + "COUNTY" + '"' + " IN ('{}')".format(v)
arcpy.SelectLayerByAttribute_management(fc, 'NEW_SELECTION',qry)
Below is attachment of attribute field with county names.
Solved! Go to Solution.
Luis, have you tried saving a snippet that works manually, then load the '*.cal' file in a text editor and check to see what format is used?
What you are seeing in the GUI isn't a double quote but two single quotes. It isn't a Python thing, but a SQL thing, i.e., in SQL you use a double single quote to escape a single quote.
Yes that worked! So in dictionary, for example Prince George's, I changed item to "Prince George\'s": "Prince George\'\'s" and it worked. Thank you all for your help! Updated code below.
import arcpy
fc = "Maryland_County_Boundaries"
CountyDict = {
"Allegany": "Allegany",
"Anne Arundel": "Anne Arundel",
"Baltimore": "Baltimore",
"Calvert": "Calvert",
"Caroline": "Caroline",
"Carroll": "Carroll",
"Cecil": "Cecil",
"Charles": "Charles",
"Dorchester": "Dorchester",
"Frederick": "Frederick",
"Garrett": "Garrett",
"Harford": "Harford",
"Howard": "Howard",
"Kent": "Kent",
"Montgomery": "Montgomery",
"Prince George\'s": "Prince George\'\'s",
"Queen Anne\'s": "Queen Anne\'\'s",
"St. Mary\'s": "St. Mary\'\'s",
"Somerset": "Somerset",
"Talbot": "Talbot",
"Washington": "Washington",
"Wicomico": "Wicomico",
"Worcester": "Worcester"
}
for k,v in CountyDict.items():
if k == "Prince George's":
qry = '"' + "COUNTY" + '"' + " IN ('{}')".format(v)
arcpy.SelectLayerByAttribute_management(fc, 'NEW_SELECTION',qry)