Python 将dict与TEMPLATE.format()一起使用时获取密钥错误
对此感到茫然。我得到一个键错误,但我不明白为什么,因为引用的键看起来像是在dict中 有什么帮助吗Python 将dict与TEMPLATE.format()一起使用时获取密钥错误,python,string,python-3.x,dictionary,formatting,Python,String,Python 3.x,Dictionary,Formatting,对此感到茫然。我得到一个键错误,但我不明白为什么,因为引用的键看起来像是在dict中 有什么帮助吗 TEMPLATE = "{ticker:6s}:{shares:3d} x {price:8.2f} = {value:8.2f}" report = [] stock = {'ticker': 'AAPL', 'price': 128.75, 'value': 2575.0, 'shares': 20} report.append(TEMPLATE.format(stock)) 这是我得
TEMPLATE = "{ticker:6s}:{shares:3d} x {price:8.2f} = {value:8.2f}"
report = []
stock = {'ticker': 'AAPL', 'price': 128.75, 'value': 2575.0, 'shares': 20}
report.append(TEMPLATE.format(stock))
这是我得到的错误:
report.append(TEMPLATE.format(stock))
KeyError: 'ticker'
您需要将
**
放在dictionary参数前面。那么,您的最后一行是:
report.append(TEMPLATE.format(**stock))
它应该会起作用
因此,您的代码应该是:
TEMPLATE = "{ticker:6s}:{shares:3d} x {price:8.2f} = {value:8.2f}"
report = []
stock = {'ticker': 'AAPL', 'price': 128.75, 'value': 2575.0, 'shares': 20}
report.append(TEMPLATE.format(**stock))
相关的: