The format_map()
function is a method used in Python to substitute the values of a dictionary into a string that contains placeholders. The keys in the dictionary are matched with the placeholders in the string, and their corresponding values are inserted into the string. This function is similar to the format()
method, but it takes a dictionary as an argument for substitution.
Parameter Values
Parameter | Description |
---|---|
mapping | A |
Return Values
The format_map()
method can return strings of any content based on a mapping.
How to Use format_map()
in Python
Example 1:
Returns a formatted version of the string using a mapping of placeholders to values
data = {'name': 'Alice', 'age': 30}
print('My name is {name} and I am {age} years old'.format_map(data))
Example 2:
If a key is missing in the mapping, it raises a KeyError
data = {'name': 'Bob'}
try:
print('My name is {name} and I am {age} years old'.format_map(data))
except KeyError as e:
print('KeyError:', e)
Example 3:
Can be used with custom classes by implementing __getitem__ method
class CustomMapping:
def __getitem__(self, key):
return 'Value'
custom_map = CustomMapping()
print('My key is {key}'.format_map(custom_map))