Using Python String format_map()

Python String Format Map

In this article, we’ll take a look at thePython String format_map() method.

This method returns a formatted version of the string using a map-based substitution, using curly brackets {}.

Let’s understand this properly, using a few examples.


Basics of Python String format_map()

The Python String format_map() function is available from Python 3.2 onward, so make sure you’re using the updated versions of Python and not the legacy ones.

The basic syntax of this String method is as follows:

substituted_string = str.format_map(mapping)

Here, mapping can be any mapping, like a Dictionary. A mapping can be viewed to be of the form {key: value}.

The Python String format_map() method replaces all keys in the string with the value.

This will return a new string, with all substitutions made, if applicable.

To understand this better, consider a mapping dictionary below:

dict_map = {"prog_lang": "Python", "site": "AskPython"}

Now, consider a format string having the keys of the dictionary under the format substitution (curly brackets).

fmt_string = "Hello from {site}. {site} is a site where you can learn {prog_lang}"

Now, we can substitute all occurences of {site} with “AskPython” and all occurences of {prog_lang} with “Python” using format_map().

print(fmt_string.format_map(dict_map))

Output

Hello from AskPython. AskPython is a site where you can learn Python

We get our desired output, with all substitutions!

Now, what if we have an extra format which does not exist on the mapping dictionary?

dict_map = {"prog_lang": "Python", "site": "AskPython"}
fmt_string = "Hello from {site}. {site} is a site where you can learn {prog_lang}. What about {other_lang}?"
print(fmt_string.format_map(dict_map))

Output

Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    print(fmt_string.format_map(dict_map))
KeyError: 'other_lang'

We get a KeyError exception. Since {other_lang} does not belong to the mapping dictionary, the lookup will fail!


A Comparison of Python String format_map() vs format()

As you may recall, the format() method is also very similar, by making suitable substitutions on a format string.

The difference can be summarized below:

  • The format() method indirectly performs a substitution using the parameters of the method, by creating a mapping dictionary first, and then performing the substitution.
  • In the case of Python String format_map(), the substitution is done using a mapping dictionary, directly.
  • Since format_map() also does not make a new dictionary, it is slightly faster than format().
  • format_map() can also use a dictionary subclass for mapping, whereas format() cannot.

To illustrate the last point, let’s create a Class which is a sub-class of dict.

We’ll experiment with both the above methods, and also try to handle any missing keys using the __missing__() dunder method.

class MyClass(dict):
    def __missing__(self, key):
        return "#NOT_FOUND#"

fmt_string = "Hello from {site}. {site} is a site where you can learn {prog_lang}."

my_dict = MyClass(site="AskPython")

print(fmt_string.format_map(my_dict))

Output

Hello from AskPython. AskPython is a site where you can learn #NOT_FOUND#.

What’s happening here? Since we have only added {site: AskPython} on our mapping dictionary, the {prog_lang} key is missing.

Therefore, “#NOT_FOUND#” is returned by the __missing__() method.

What if we use format()?

fmt_string.format(my_dict)

Output

Traceback (most recent call last):
  File "<pyshell#14>", line 1, in <module>
    fmt_string.format(my_dict)
KeyError: 'site'

Well, format() does not handle this for us, and it simply raises a KeyError exception. This is because it copies the mapping to a new dictionary object.

Because the mapping is on a new dictionary object (not using our subclass), it does not have the __missing__ method! Therfore, it can only give a KeyError!


Conclusion

In this article, we learned about how we could use the Python String format_map() method to perform substitutions on a format string. We also saw a quick comparison with the format() method.

References

  • JournalDev article on String format_map()