Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.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 3.x Python 3.2:如何将字典传递到str.format()中_Python 3.x_Dictionary_String Formatting_Keyword Argument - Fatal编程技术网

Python 3.x Python 3.2:如何将字典传递到str.format()中

Python 3.x Python 3.2:如何将字典传递到str.format()中,python-3.x,dictionary,string-formatting,keyword-argument,Python 3.x,Dictionary,String Formatting,Keyword Argument,我一直在阅读关于字符串格式的Python3.2文档,但它并没有真正帮助我解决这个问题 以下是我想做的: stats = { 'copied': 5, 'skipped': 14 } print( 'Copied: {copied}, Skipped: {skipped}'.format( stats ) ) 上面的代码将不起作用,因为format()调用没有读取字典值并使用这些值代替我的format占位符。如何修改代码以使用字典?您需要.format(**stats),因为这使stats成为f

我一直在阅读关于字符串格式的Python3.2文档,但它并没有真正帮助我解决这个问题

以下是我想做的:

stats = { 'copied': 5, 'skipped': 14 }
print( 'Copied: {copied}, Skipped: {skipped}'.format( stats ) )
上面的代码将不起作用,因为format()调用没有读取字典值并使用这些值代替我的format占位符。如何修改代码以使用字典?

您需要
.format(**stats)
,因为这使stats成为format的kwargs的一部分。

这样做:

stats = { 'copied': 5, 'skipped': 14 }
print( 'Copied: {copied}, Skipped: {skipped}'.format( **stats ) )  #use ** to "unpack" a dictionary
有关更多信息,请参阅:


为什么这一次的得票较少?它有更多的信息(指向文档的链接)和更好的示例