python - 使用带有 TEMPLATE.format() 的字典时出现关键错误

标签 python string python-3.x dictionary formatting

对此感到茫然。我收到一个 key 错误,但我不明白为什么,因为引用的 key 看起来像是在字典中。

有什么帮助吗?

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()

关于python - 使用带有 TEMPLATE.format() 的字典时出现关键错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29872283/

相关文章:

python - "ValueError: could not convert string to float"转换输入时

python - 如何更改 matplotlib 中的 x 轴以便没有空格?

android - Android:如何在Kotlin中将string.xml中的R.string值设置为全局常量?

python dataframe根据其他列的条件替换列中的部分字符串

python - 无法加载 pickle 对象

python - Pygame 迷宫游戏无法正确创建关卡

python - Pandas:如何在稀疏表中选择具有非零值的列

python - 查找长字符串中给定单词之前的\n 数量

python - 计算每个月的支出金额,这取决于另一个列值 ID

python - 如何使用分而治之的多线程?