Python String format_map() Method
The format_map()
method is used to format strings by substituting placeholders with values from a dictionary or any other mapping object.
It is similar to format()
method but takes a mapping object (dictionary) directly rather than unpacking it with **
.
Syntax
string.format_map(mapping)
Parameters
mapping
: A dictionary (or any mapping object) containing keys and their corresponding values to insert into the string.
Return Value
Returns a new string with the placeholders replaced by the values from the mapping (dictionary).
Examples
Format a String Using Values From a Dictionary
person = {"name": "James", "age": 35}
print("My name is {name} and I am {age} years old.".format_map(person))
# Output: My name is James and I am 35 years old.
Handling Missing Keys
If a key in the string’s placeholder does not exist in the mapping (dictionary), it raises KeyError
.
You can handle this missing key error by creating a custom dictionary subclass.
class SafeDict(dict):
def __missing__(self, key):
return f'[{key}]' # Return key in brackets if missing
person = {"name": "James", "age": 35}
print("My name is {name}, my age is {age} and I live in {address}.".format_map(SafeDict(person)))
# Output: My name is James, my age is 35 and I live in [address].