Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/kotlin/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将dict与TEMPLATE.format()一起使用时获取密钥错误_Python_String_Python 3.x_Dictionary_Formatting - Fatal编程技术网

Python 将dict与TEMPLATE.format()一起使用时获取密钥错误

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)) 这是我得

对此感到茫然。我得到一个键错误,但我不明白为什么,因为引用的键看起来像是在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))
这是我得到的错误:

    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))
相关的: