Skip to content

Python String format_map() Method

How to use Python's format_map() method to dynamically format strings with dictionary mappings, including handling missing keys and subclass dictionaries.

The String format_map() method formats a string using a mapping object, such as a dictionary, where the keys in the string are replaced by their corresponding values from the mapping.

Syntax

template_str.format(mapping)

format_map() Parameters

Python String format_map() method parameters:

Parameter Condition Description
mapping Required A mapping of placeholders to values, like a Dictionary

format_map() Return Value

Python String format_map() method returns a formatted version of the string using a mapping of placeholders to values.

Examples

Example 1: Basic usage of format_map()

Let's see a first example that shows how to use format_map() with a dictionary to replace placeholders in a string with corresponding values from the dictionary.

data = {'name': 'David', 'age': 25}
print('My name is {name} and I am {age} years old'.format_map(data))

output

My name is David and I am 25 years old

Example 2: Handing missing keys in format_map()

format_map() is more flexible than format() because you can have missing keys.

If there is a missing key, a KeyError exception is thrown.

data = {'name': 'David'}
print('My name is {name} and I am {age} years old'.format_map(data))

output

Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print('My name is {name} and I am {age} years old'.format_map(data))
KeyError: 'age'

As usual, you can handle exceptions use try-catch statement.

data = {'name': 'David'}
try:
    print('My name is {name} and I am {age} years old'.format_map(data))
except KeyError as e:
    print('KeyError:', e)

output

KeyError: 'age'

Example 3: Working with sub Dict and missing keys in the mapping for format_map()

Instead of throwing an exception, you can handle missing keys by returning the key itself if it is not found in the dictionary.

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

print('({x}, {y})'.format_map(Coordinate(x='1'))) # Output: (1,y)
print('({x}, {y})'.format_map(Coordinate(y='2'))) # Output: (x,2)
print('({x}, {y})'.format_map(Coordinate(x='1', y='2'))) # Output: (1,2)

output

(1, y)
(x, 2)
(1, 2)
Navigation