Selecting records from feature class that have special characters using a dictionary (python)

1392
12
Jump to solution
07-26-2019 06:34 AM
LuisResh
New Contributor II

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.

Tags (1)
0 Kudos
12 Replies
DanPatterson_Retired
MVP Emeritus

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?

0 Kudos
JoshuaBixby
MVP Esteemed Contributor

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.

LuisResh
New Contributor II

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)

0 Kudos