【问题标题】:Getting a key error while using a dict with TEMPLATE.format()使用带有 TEMPLATE.format() 的字典时出现关键错误
【发布时间】:2015-04-26 00:25:14
【问题描述】:

对此不知所措。我收到一个键错误,但我不知道为什么引用的键看起来像在字典中。

有什么帮助吗?

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'

【问题讨论】:

    标签: python string python-3.x dictionary formatting


    【解决方案1】:

    您需要将** 放在字典参数的前面。所以,你的最后一行是:

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

    【讨论】:

      猜你喜欢
      • 2020-10-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多