Python String format_map()

The format_map() method is similar to str.format(**mapping) except that str.format(**mapping) creates a new dictionary whereas str.format_map(mapping) doesn't.

Before talking about format_map(). Let's see how str.format(**mapping) works for Python Dictionaries.

point = {'x':4,'y':-5}
print('{x} {y}'.format(**point))

When you run the program, the output will be:

4 -5

Learn more on, how to format strings in Python?


The format_map(mapping) is similar to str.format(**mapping) method.

The only difference is that, the str.format(**mapping) copies the dict whereas str.format_map(mapping) makes a new dictionary during method call. This can be useful if you are working with a dict subclass.


The syntax of the format_map() is

str.format_map(mapping)

format_map Parameter

The format_map() takes a single argument mapping(dictionary).


Return Value from format_map()

The format_map() formats the given string and returns it.


Example 1: How format_map() works?

point = {'x':4,'y':-5}
print('{x} {y}'.format_map(point))

point = {'x':4,'y':-5, 'z': 0}
print('{x} {y} {z}'.format_map(point))

When you run the program, the output will be:

4 -5
4 -5 0

Example 2: How format_map() works with dict subclass?

class Coordinate(dict):
    def __missing__(self, key):
      return key


print('({x}, {y})'.format_map(Coordinate(x='6')))
print('({x}, {y})'.format_map(Coordinate(y='5')))
print('({x}, {y})'.format_map(Coordinate(x='6', y='5')))

When you run the program, the output will be:

(6, y)
(x, 5)
(6, 5)

The format_map(mapping) is more flexible than format(**mapping) as you can have missing keys.