gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 04:44:07 25 4
gpt4 key购买 nike

对此感到茫然。我收到一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com