Python String format_map()
Method
The format_map() method in Python is used to format a string using a dictionary or any mapping object. It's similar to str.format()
, but instead of passing variables as keyword arguments, you pass a dictionary.
Syntax
string.format_map(mapping)
Parameters:
mapping
– A dictionary or mapping object containing keys that match the placeholders in the string.
Returns:
- A formatted string where placeholders are replaced by corresponding values from the mapping.
Example 1: Basic Usage with Dictionary
person = {"name": "Alice", "age": 30}
text = "Name: {name}, Age: {age}".format_map(person)
print(text)
Name: Alice, Age: 30
Example 2: Using with Custom Mapping
class DefaultDict(dict):
def __missing__(self, key):
return 'N/A'
info = DefaultDict(name="Bob")
print("Name: {name}, City: {city}".format_map(info))
Name: Bob, City: N/A
This technique is useful when some keys might be missing in the dictionary.
Difference Between format()
and format_map()
format()
uses keyword arguments:"{name}".format(name="John")
format_map()
uses a dictionary:"{name}".format_map({"name": "John"})
format_map()
cannot take multiple types of arguments likeformat()
Common Mistakes
- Passing a non-dictionary object will raise a
TypeError
. - If the key is missing in the mapping, it raises a
KeyError
unless handled using__missing__
.
Use Cases
- When formatting templates with predefined values.
- Building strings from JSON or config files.
- Useful in logging or templating systems where data is dictionary-based.
Interview Tip
Use format_map()
when formatting strings from dynamic dictionaries. It's helpful when you can't hardcode keys into the function call.
Summary
format_map()
formats a string using a dictionary.- It is similar to
format()
but takes a single mapping object. - Use custom mappings to handle missing keys gracefully.
Practice Problem
Create a program that takes user input (name and score) and formats the output using format_map()
.
data = {"name": input("Enter your name: "), "score": input("Enter your score: ")}
template = "Player: {name} | Score: {score}"
print(template.format_map(data))