How to Format a Dictionary in Python

Python's format() method makes it easy and intuitive to format data from a dictionary into a string.

string.format()

This method is especially useful for creating display templates and custom messages.

Example

Let's create a dictionary with three key-value pairs: first name, last name, and year.

anagrafica = {'nome':'Andrea', 'cognome':'Minini', 'anno':2018 }

It’s a simple example, but it serves its purpose.

Next, we'll define a string using the format() method.

We’ll place placeholders inside curly braces {} that correspond to the dictionary's keys.

stringa = 'My name is {nome} {cognome} and the year is {anno:d}'.format(**anagrafica)

The placeholders {nome} and {cognome} are strings, while {anno} is an integer (d).

In the format method, you reference the dictionary by using two asterisks as a prefix.

Finally, print the formatted string using the print() function.

print(stringa)

The output will be:

My name is Andrea Minini and the year is 2018

The placeholders are replaced with the corresponding values from the dictionary.

And that’s it!

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Python

  1. The Python Language
  2. How to Install Python on Your PC
  3. How to Write a Program in Python
  4. How to Use Python in Interactive Mode
  5. Variables
  6. Numbers
  7. Logical Operators
  8. Iterative Structures (or Loops)
  9. Conditional Structures
  10. Exceptions
  11. Files in Python
  12. Classes
  13. Modules

Miscellaneous

Source