
Definition
In Python, format_map() fills named {key} placeholders using values from a mapping, usually a dict.
mapping is required. A missing key raises KeyError unless the mapping defines __missing__.
Syntax
Call format_map with a mapping. Start with this line.
msg = "Hello, {name}!".format_map(data)
| Call | What it does |
|---|
"{x}".format_map({"x": 1}) | Fills {x} from a dict. |
template.format_map(vars(obj)) | Uses object attributes as keys. |
Prefer format_map for mapping objects. Use format() when you need positional {} fields.
Library declarations
str.format_map(mapping) → str
Parameters
| Parameter | Description |
|---|
| mapping | Required. A dict-like object with values for each placeholder key. |
Return Value
| Return Value | Description |
|---|
| str | A new string with named placeholders replaced. |
Python Examples
Example 1 — Fill from a Dictionary
Keys in the dict must match the placeholder names.
data = {"name": "Ada", "score": 95}
msg = "{name} scored {score}".format_map(data)
print(msg)
# specifiers still work
print("{score:.1f}%".format_map({"score": 95}))
How It Works
- Build a mapping. Keys are
name and score. - Call format_map. Each
{key} looks up that key. - Get a new string. Template text is unchanged.
- Use specifiers.
{score:.1f} formats the looked-up value.
Example 2 — format_map vs format(**data)
For a plain dict the result matches; the calling style differs.
data = {"city": "Chennai", "temp": 32}
template = "Weather in {city}: {temp}°C"
print(template.format_map(data))
print(template.format(**data))
Weather in Chennai: 32°C
Weather in Chennai: 32°C
How It Works
- Same template. Named fields only.
- format_map passes the dict. No unpacking step.
- format(**data) unpacks. Keywords become the same fields.
- Prefer format_map when the mapping is custom or should stay intact.
Example 3 — Default for Missing Keys
A small SafeDict leaves unknown fields visible instead of crashing.
class SafeDict(dict):
def __missing__(self, key):
return "{" + key + "}"
template = "Hello, {name}. Role: {role}"
data = SafeDict(name="Ada")
print(template.format_map(data))
# Hello, Ada. Role: {role}
How It Works
- Subclass dict. Override
__missing__ for absent keys. - Return a placeholder string. Here we echo
{role}. - Present keys still work.
name fills normally. - No KeyError. Useful for partial data / templates.
Frequently Asked Questions
It fills named placeholders from a mapping and returns a new string.
format_map takes one mapping. format() takes positional and keyword arguments.
A normal dict raises KeyError.
Yes. Pass vars(obj) when placeholders match attribute names.
No. Strings are immutable.
About the author
Developer, cloud engineer, and technical writer
I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.
9 people found this page helpful