Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 428
void.pointer Avatar asked Jun 26 '11 23:06

void.pointer


People also ask

What is str format in Python?

Python String format() The string format() method formats the given string into a nicer output in Python. The syntax of the format() method is: template.


2 Answers

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
like image 155
pawroman Avatar answered Sep 20 '22 08:09

pawroman


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

like image 35
Dan D. Avatar answered Sep 20 '22 08:09

Dan D.