Python str.format_map() function


In Python, the str.format_map() method is used to format strings in a similar way to str.format(), but it takes a single mapping object (like a dictionary) as an argument. This allows you to use the keys of the mapping directly in the string placeholders, which can lead to cleaner and more concise code.

Syntax

str.format_map(mapping)
  • mapping: A dictionary or any other object that implements the mapping protocol (like an instance of collections.abc.Mapping).

Example Usage

  1. Basic usage with a dictionary:

You can use a dictionary to provide values for placeholders in the string:

data = {'name': 'Alice', 'age': 30} formatted_string = "My name is {name} and I am {age} years old.".format_map(data) print(formatted_string) # Output: "My name is Alice and I am 30 years old."
  1. Using a custom mapping object:

You can create a custom mapping object that implements the __getitem__ method:

class CustomMapping: def __getitem__(self, key): if key == 'name': return 'Bob' elif key == 'age': return 25 raise KeyError(key) custom_data = CustomMapping() formatted_string = "My name is {name} and I am {age} years old.".format_map(custom_data) print(formatted_string) # Output: "My name is Bob and I am 25 years old."
  1. Handling missing keys:

If a key in the mapping is not found, format_map() raises a KeyError. This is different from str.format(), which allows for missing keys if you use default values with the get method or provide a fallback.

data = {'name': 'Alice'} try: formatted_string = "My name is {name} and I am {age} years old.".format_map(data) except KeyError as e: print(f"Key error: {e}") # Output: "Key error: 'age'"
  1. Using with nested mappings:

You can also format strings with nested dictionaries:

data = { 'user': { 'name': 'Charlie', 'age': 28 } } formatted_string = "User: {user[name]}, Age: {user[age]}".format_map(data) print(formatted_string) # Output: "User: Charlie, Age: 28"

Summary

  • Use str.format_map() to format strings using a single mapping object, such as a dictionary.
  • This method allows for a cleaner syntax by directly accessing the keys in the mapping within the string placeholders.
  • Unlike str.format(), it raises a KeyError if a key is not found, which can help catch missing data early in the development process.
  • It's particularly useful when you want to format strings based on dynamic data structures like dictionaries or custom mapping objects.