我尝试在format()函数中将多个参数作为dict发送,但我收到此错误:
import UIKit
class tableOutlineViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var tableView: UITableView!
var names = ["Max", "Bill", "Reagan", "Mikayla", "Jessie", "Sierra", "Jeff", "Erik", "Landon"]
var numbers = ["35", "33", "29", "27", "25", "23", "19", "15", "11"]
var photo = [UIImage(named: "Person1"), UIImage(named: "Person2"), UIImage(named: "Groceries"), UIImage(named: "Person3"), UIImage(named: "Person4"), UIImage(named: "Person5"), UIImage(named: "Person6"), UIImage(named: "Person7")]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = self.tableView.dequeueReusableCell(withIdentifier: "CustomCell") as! CustomCell
cell.images.image = photo[indexPath.row]
cell.name.text = names[indexPath.row]
cell.number.text = numbers[indexPath.row]
return cell
}
}
这是我的代码:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 4, in open_query
KeyError: 'asset_name'
参数可以是以下之一:
def open_query(query_file,parameters):
fd = open(query_file, 'r')
query = fd.read()
query = query.format(parameters)
fd.close()
return query
或
parameters = {'date_':my_date,'instrument':'BTC_ETH'}
我该如何解决这个问题?
答案 0 :(得分:2)
您想要对字典进行双重处理,但您还需要为模板字符串指定值。
举个例子,
>>> params={"a":1, "foo":"bar"}
>>> "There is {a} {foo}".format(**params)
'There is 1 bar'
如果需要,您还可以查看Jinja2 / Mako模板。
答案 1 :(得分:1)
正如 cricket_007 写的那样,您应该使用**解包参数dict
query.format(**parameters)
但是你的其他输入仍然会失败
parameters = {'date_':my_date,'instrument':'BTC_ETH'}
query = "{assent_name}"
query.format(**parameters)
KeyError:'assent_name'
您应该考虑这个案例并解决它。也许使用默认字典
from collections import defaultdict
paramerters = defaultdict(lambda : "N/A")
print("{assent_name}".format_map(paramerters))