31

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

2 Answers 2

68

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:

1
  • 1
    Why did this one get less up-votes? It has more information (links to docs) and a better example. Jun 27, 2011 at 14:49
16

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.