29

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?

dreftymac
  • 29,742
  • 25
  • 114
  • 177
void.pointer
  • 23,191
  • 28
  • 120
  • 213
  • Possible duplicate of https://stackoverflow.com/questions/5952344/how-do-i-format-a-string-using-a-dictionary-in-python-3-x – Frank May 16 '19 at 20:17

2 Answers2

63

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:

pawroman
  • 1,220
  • 8
  • 12
16

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

Dan D.
  • 70,581
  • 13
  • 96
  • 116