str.format_map()
The reason it exists: format(**m) copies m into a new dict, so a custom mapping loses its behaviour. format_map passes the object through untouched.
Demo
Each {key} is looked up in the mapping and replaced by the value. Keys the template never mentions are simply unused, and a key the template needs but the mapping lacks raises KeyError naming it. Everything here is also true of format(**mapping) — the difference only shows once the mapping is not a plain dict, because format copies it and format_map does not.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| mapping | mapping | yes | Any object supporting __getitem__ — a dict, a defaultdict, or a custom class. It is used directly, never copied. |
Return value
str — A new string with each {key} replaced by mapping[key]. Raises KeyError for a placeholder the mapping cannot supply.
Common patterns
from collections import defaultdict s.format_map(defaultdict(str, name="Ada"))
class Keep(dict): def __missing__(self, key): return "{" + key + "}" s.format_map(Keep(name="Ada"))
template.format_map(config) # config[key] on demand
Examples
Pitfalls
from collections import defaultdict '{a}'.format(**defaultdict(str))
'{a}'.format_map(defaultdict(str))
user_template.format_map(ctx)
FIXED_TEMPLATE.format_map(user_values)
'{a} }'.format_map({'a': 1})
'{a} }}'.format_map({'a': 1})
'{name}'.format_map(name='Ada')
'{name}'.format_map({'name': 'Ada'})
When to use
- The mapping is a defaultdict or defines __missing__
- The mapping is large and copying it would be wasteful
- Keys are computed lazily by a custom __getitem__
- Keys are not valid Python identifiers, so ** cannot express them
- A plain dict with all keys present → format(**d) reads more familiarly
- Templates from users → string.Template is far safer
- Simple interpolation of local variables → an f-string
Notes
FAQ
Only in how the mapping arrives. ** unpacks it into a fresh plain dict, so anything special about the original — __missing__, laziness, non-identifier keys — is gone. format_map hands the object straight to the formatter, so all of that still works.
'{a}'.format_map(defaultdict(str)) # '' '{a}'.format(**defaultdict(str)) # KeyError