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!