String Methods

str.format_map()

Resolve named replacement fields directly against the supplied mapping rather than expanding its entries into a separate keyword dictionary. This supports custom item lookup and dictionary subclasses with __missing__ behavior. Ordinary absent keys raise KeyError unless the mapping supplies another result. Positional fields are not accepted, but indexing and attribute access after a named field work, as do conversions and format specifications. The same trusted-template precautions as str.format apply.

Formal Syntax & Structure

python syntaxpython
template.format_map(mapping, /)

Parameters & Attributes

NameTypeDescription
mappingMapping[str, object]Object providing lookup for field names; used directly.

Return Value

str

Text with named fields substituted.

Working Example

Example Snippetpython
class Defaults(dict):    def __missing__(self, key):        return "unknown"
profile = Defaults(name="سارا", score=7)template = "{name}: {score:03d} ({city})"print(template.format_map(profile))print("{item[price]:.2f}".format_map({"item": {"price": 4.5}}))
Python Reference