Python string format_map() function returns a formatted version of the string using substitutions from the mapping provided. The substitution arguments are present in the string and identified by curly braces ({ }).
Python String format_map()
This function was introduced in Python 3.2. It’s syntax is:
str.format_map(mapping)
Let’s look at some examples of format_map() function.
s = 'My name is {name} and I am a {job_title}'
my_dict = {'name': 'Pankaj', 'job_title': 'Software Engineer'}
print(s.format_map(my_dict))
print(s.format(**my_dict))
Output:
My name is Pankaj and I am a Software Engineer
My name is Pankaj and I am a Software Engineer
What if the mapping contains more keys than we actually need in the formatting?
my_dict = {'name': 'Meghna', 'job_title': 'Writer', 'company': 'JournalDev'}
print(s.format_map(my_dict))
print(s.format(**my_dict))
Output:
My name is Meghna and I am a Writer
My name is Meghna and I am a Writer
What if the mapping has missing keys?
my_dict = {'name': 'Pankaj'}
print(s.format_map(my_dict))
Output: KeyError: 'job_title'
Let’s see the output if we use string format() function.
print(s.format(**my_dict))
Output: KeyError: 'job_title'
format_map() vs format()
Python string format_map() function is very similar to format() function. The only difference is that the mappings are used directly and not copied to a dictionary. This is useful when the mapping is a dict subclass.
If you look at the above examples, the format() and format_map() function behavior is exactly the same. Let’s see how it differs when the mapping is a subclass of dict.
class MyDict(dict):
def __missing__(self, key):
return '#Not Found#'
s = 'My name is {name} and I am a {job_title}'
my_dict = MyDict(name='Pankaj')
print(my_dict)
print(s.format_map(my_dict))
Output: My name is Pankaj and I am a #Not Found#
So when the key is missing, __missing__ function is called and the output is used to replace the substitution.
Let’s see what happens if we try to use format() function here.
print(s.format(**my_dict))
Output: KeyError: 'job_title'
String format() function is throwing an error because it’s copying the provided mappings to a new dict object. So the subclass where we have implemented __missing__ function is never used and hence the error.
Conclusion
Python String format_map() function is useful when we want to use a dict subclass for mapping purposes. Since the mapping is used directly, the functions from the subclass get called whereas if we use format() function then mappings are copied to a new dict object and our subclass functions will not be called.
Reference: Official Documentation