Skip to main content

Python String format_map() Function

The String format_map() method formats a string using a mapping object, such as a dictionary, where the keys in the string are replaced by their corresponding values from the mapping.

note

Unlike the format() method, which also supports dictionary-based formatting but copies the dictionary, format_map() creates a new dictionary during the method call, which can be beneficial when working with dictionary subclasses.

note

Formatting options of format_map() are the same of format(). See format() method for more details about formatting options.

Syntax

template_str.format(mapping)

format_map() Parameters

Python String format_map() function parameters:

ParameterConditionDescription
mappingRequiredA mapping of placeholders to values, like a Dictionary

format_map() Return Value

Python String format_map() function returns a formatted version of the string using a mapping of placeholders to values.

Examples

Example 1: Basic usage of format_map()

Let's see a first example that shows how to use format_map() with a dictionary to replace placeholders in a string with corresponding values from the dictionary.

data = {'name': 'David', 'age': 25}
print('My name is {name} and I am {age} years old'.format_map(data))

output

My name is David and I am 25 years old

Example 2: Handing missing keys in format_map()

format_map() is more flexible than format() because you can have missing keys.

If there is a missing key, a KeyError exception is thrown.

data = {'name': 'David'}
print('My name is {name} and I am {age} years old'.format_map(data))

output

Traceback (most recent call last):
File "main.py", line 2, in <module>
print('My name is {name} and I am {age} years old'.format_map(data))
KeyError: 'age'

As usual, you can handle exceptions use try-catch statement.

data = {'name': 'David'}
try:
print('My name is {name} and I am {age} years old'.format_map(data))
except KeyError as e:
print('KeyError:', e)

output

KeyError: 'age'

Example 3: Working with sub Dict and missing keys in the mapping for format_map()

Instead of throwing an exception, you can handle missing keys by returning the key itself if it is not found in the dictionary.

class Coordinate(dict):
def __missing__(self, key):
return key

print('({x}, {y})'.format_map(Coordinate(x='1'))) # Output: (1,y)
print('({x}, {y})'.format_map(Coordinate(y='2'))) # Output: (x,2)
print('({x}, {y})'.format_map(Coordinate(x='1', y='2'))) # Output: (1,2)

output

(1, y)
(x, 2)
(1, 2)