Python String format_map()

1. Overview

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))

Output

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 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 format_map() is

str.format_map(mapping)

2. format_map Parameter

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

3. Return Value from format_map()

format_map() formats the given string and returns it.

4. 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))

Output

4 -5
4 -5 0

5. 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')))

Output

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

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