str.format_map()

str.format_map(mapping)
Returns: str · Updated March 13, 2026 · String Methods
strings formatting mapping

The format_map() method formats the string using a mapping object directly. It works similarly to .format() but accesses the mapping without calling .keys(), making it compatible with dict-like objects that have dynamic or computed keys.

Syntax

str.format_map(mapping)

Parameters

ParameterTypeDescription
mappingMappingA dict-like object implementing __getitem__ for key access

Returns: A formatted string.

How It Works

Unlike .format(**mapping) which copies the dictionary, format_map() uses the mapping directly. This matters when you’re working with dict subclasses that have custom behavior, like a Default dict that returns a default value for missing keys.

# format() requires the dict to have all keys
data = {'name': 'Alice'}
'{name} {age}'.format(**data)  # KeyError: 'age'

# format_map() can work with objects that handle missing keys
class Default(dict):
    def __missing__(self, key):
        return key

'{name} {age}'.format_map(Default(name='Alice'))
# Alice age

Examples

Basic usage with a dictionary

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

Using a defaultdict

from collections import defaultdict

data = defaultdict(lambda: 'unknown')
data['name'] = 'Bob'

'{name} {status}'.format_map(data)
# Bob unknown

The defaultdict returns 'unknown' for the missing status key instead of raising an error.

Custom mapping with computed values

class NumberSquarer:
    def __getitem__(self, key):
        return str(int(key.lstrip('n')) ** 2)

'{n17} squared is {n20}'.format_map(NumberSquarer())
# 289 squared is 400

This works because format_map() only needs __getitem__, not keys().

Difference from format(**mapping)

class UserDict(dict):
    pass

data = UserDict(name='Charlie')

# format() copies the dict - loses subclass behavior
'{name}'.format(**data)
# Charlie

# format_map() uses it directly - preserves subclass behavior
'{name}'.format_map(data)
# Charlie

The practical difference appears when the dict subclass has custom __missing__ or other special methods.

When to Use format_map()

Use format_map() when:

  • You need to preserve dict subclass behavior (like defaultdict or ChainMap)
  • You’re working with objects that implement __getitem__ but not keys()
  • You want to avoid copying a large mapping

Stick with .format() or f-strings for simple cases with regular dictionaries.

Errors

ExceptionWhen it occurs
KeyErrorA key in the format string is not found and the mapping has no __missing__ method
TypeErrorThe mapping doesn’t support __getitem__

See Also