ed.hank
ed.hank

Reputation: 111

Can you use {} and .format to put values into a dictionary

I am writing a script to query an ArcGIS rest service and return records. I want to use {} and .format to allow a dictionary item to be changed a time. How do I write this:

time = '2016-10-06 19:18:00'
URL = 'http://XXXXXXXXX.gov/arcgis/rest/services/AGO_Street/StreetMaint_ServReqs/FeatureServer/10/query'
params = {'f': 'pjson', 'where': "CLOSE_DATE > '{}'", 'outfields' : 'OBJECTID, REPORTED_DATE, SUMMARY, ADDRESS1, REQUEST_STATUS, CLOSE_DATE, INCIDENT_NUMBER', 'returnGeometry' : 'false'}.format(time)
req = urllib2.Request(URL, urllib.urlencode(params))

if I use this for param it will work

params = {'f': 'pjson', 'where': "CLOSE_DATE > '2016-10-06 19:18:00'", 'outfields' : 'OBJECTID, REPORTED_DATE, SUMMARY, ADDRESS1, REQUEST_STATUS, CLOSE_DATE, INCIDENT_NUMBER', 'returnGeometry' : 'false'}

What is the proper python formatting to do this?

Upvotes: 0

Views: 56

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1124070

str.format is a string method, not a method on a dictionary. Just apply the method to that one string value:

params = {
    'f': 'pjson', 
    'where': "CLOSE_DATE > '{}'".format(time),
    'outfields' : 'OBJECTID, REPORTED_DATE, SUMMARY, ADDRESS1, REQUEST_STATUS, CLOSE_DATE, INCIDENT_NUMBER',
     'returnGeometry' : 'false'
}

Each of the key and value parts in a dictionary definition is just another expression, you are free to use any valid Python expression to produce the value, including calling methods on the string and using the result as the value.

Upvotes: 3

rassar
rassar

Reputation: 5670

Try this:

'where': "CLOSE_DATE > '{}'".format(time)

Upvotes: 1

Related Questions