简体   繁体   English

您可以使用{}和.format将值放入字典中吗

[英]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. 我正在编写脚本来查询ArcGIS Rest服务并返回记录。 I want to use {} and .format to allow a dictionary item to be changed a time. 我想使用{}和.format允许一次更改字典项。 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? 什么是正确的python格式来做到这一点?

str.format is a string method , not a method on a dictionary. str.format字符串方法 ,而不是字典上的方法。 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. 字典定义中的每个部分都只是另一个表达式,您可以自由使用任何有效的Python表达式来产生值,包括在字符串上调用方法并将结果用作值。

尝试这个:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM