What is difference between str.format_map(mapping) and str.format

str.format(**kwargs) makes a new dictionary in the process of calling. str.format_map(kwargs) does not. In addition to being slightly faster, str.format_map() allows you to use a dict subclass (or other object that implements mapping) with special behavior, such as gracefully handling missing keys. This special behavior would be lost otherwise when the items were copied to a new dictionary.

See: https://docs.python.org/3/library/stdtypes.html#str.format_map


str.format(**mapping) when called creates a new dictionary, whereas str.format_map(mapping) doesn't. The format_map(mapping) lets you pass missing keys. This is useful when working per se with the dict subclass.

class Foo(dict): # inheriting the dict class
    def __missing__(self,key):
        return key
print('({x},{y})'.format_map(Foo(x='2')))  # missing key y 
print('({x},{y})'.format_map(Foo(y='3')))  # missing key x