使用带有 TEMPLATE.format() 的字典时出现关键错误
Getting a key error while using a dict with TEMPLATE.format()
对此一头雾水。我遇到了一个关键错误,但我无法弄清楚为什么引用的关键看起来像是在字典中。
有什么帮助吗?
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'
您需要在字典参数前加上**
。所以,你的最后一行是:
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))
相关:Python 3.2: How to pass a dictionary into str.format()
对此一头雾水。我遇到了一个关键错误,但我无法弄清楚为什么引用的关键看起来像是在字典中。
有什么帮助吗?
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'
您需要在字典参数前加上**
。所以,你的最后一行是:
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))
相关:Python 3.2: How to pass a dictionary into str.format()