Python String format_map()

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)

format_map Parameter

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


Return Value from format_map()

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

Output

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

Output

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

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


Also Read:

Did you find this article helpful?

Our premium learning platform, created with over a decade of experience and thousands of feedbacks.

Learn and improve your coding skills like never before.

Try Programiz PRO
  • Interactive Courses
  • Certificates
  • AI Help
  • 2000+ Challenges