Today we’ll learn how to use dictionaries to format strings.
If you haven’t read my previous articles on formatting strings, feel free to read them. Here’s the article on the basics of formatting with the format method and f-strings and here’s the article on advanced string formatting with the format method.
And now let’s go back to our topic.
You can use dictionaries for formatting. You then pass the dictionary preceded by ** to the format method. Here’s a dictionary:
>>> address = {"country" : "France", "city" : "Paris", "street" : "Avenue des Champs-Élysées"}
Now we’ll use the keys as keywords in the format fields and their values will be read in the dictionary:
>>> print("We stayed at 21 {street} in {city}, {country}.".format(**address))
We stayed at 21 Avenue des Champs-Élysées in Paris, France.
What just happened here is **address was automatically translated into:
country = “France”, city = “Paris”, street = “Avenue des Champs-Élysées”.
Alternatively, you could pass just the dictionary to the format method (without **), and use the keys directly in the format fields:
>>> print("We stayed at 21 {0[street]} in {0[city]}, {0[country]}.".format(address))
We stayed at 21 Avenue des Champs-Élysées in Paris, France.
Here we have just one positional argument passed to the format method, which is the dictionary. In the format fields we access this positional argument by index, which is 0, followed by the key in square brackets.
Local Variables
You can also create a dictionary containing all local variables available in the current scope. Such a dictionary is created by the function locals:
>>> text = "hello"
>>> number = 10
>>>
>>> print("{text}".format(**locals()))
hello
Here’s the video version of this article: