Python 3.2: How to pass a dictionary into str.format()

被刻印的时光 ゝ 提交于 2019-11-28 07:19:21

问题


I've been reading the Python 3.2 docs about string formatting but it hasn't really helped me with this particular problem.

Here is what I'm trying to do:

stats = { 'copied': 5, 'skipped': 14 }
print( 'Copied: {copied}, Skipped: {skipped}'.format( stats ) )

The above code will not work because the format() call is not reading the dictionary values and using those in place of my format placeholders. How can I modify my code to work with my dictionary?


回答1:


This does the job:

stats = { 'copied': 5, 'skipped': 14 }
print( 'Copied: {copied}, Skipped: {skipped}'.format( **stats ) )  #use ** to "unpack" a dictionary

For more info please refer to:

  • http://docs.python.org/py3k/library/string.html#format-examples and
  • http://docs.python.org/py3k/tutorial/controlflow.html#keyword-arguments



回答2:


you want .format(**stats) as that makes stats part of format's kwargs.



来源:https://stackoverflow.com/questions/6487501/python-3-2-how-to-pass-a-dictionary-into-str-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!