How to format a string using a dictionary in Python
In Python, we can use a dictionary to format strings dynamically by replacing placeholders with corresponding values from the dictionary. For example, consider the string "Hello, my name is {name} and I am {age} years old." and the dictionary {'name': 'Alice', 'age': 25}. The task is to format this string using the dictionary to produce "Hello, my name is Alice and I am 25 years old.". Let's explore several ways to achieve this.
Using str.format with Double Asterisks (**kwargs)
str.format() method allows passing dictionary values as keyword arguments using the ** operator.
# Input string and dictionary
template = "Hello, my name is {name} and I am {age} years old."
data = {'name': 'Alice', 'age': 25}
# Format the string
res = template.format(**data)
# Resulting string
print(res)
Output
Hello, my name is Alice and I am 25 years old.
Explanation:
- ** operator unpacks the dictionary into keyword arguments.
- str.format() method replaces placeholders in the string with corresponding dictionary values.
Let's explore some more ways and see how we can format a string using a dictionary in Python.
Table of Content
Using str.format_map
str.format_map() method directly formats the string using a dictionary without unpacking it.
# Input string and dictionary
template = "Hello, my name is {name} and I am {age} years old."
data = {'name': 'Alice', 'age': 25}
# Format the string
res = template.format_map(data)
# Resulting string
print(res)
Output
Hello, my name is Alice and I am 25 years old.
Explanation:
- str.format_map() method uses the dictionary directly for formatting.
- It is more concise than str.format() when working with dictionaries.
Using F-strings with Variables
For simple cases, we can use f-strings in combination with variable unpacking.
# Input dictionary
data = {'name': 'Alice', 'age': 25}
# Format the string using f-strings
res = f"Hello, my name is {data['name']} and I am {data['age']} years old."
# Resulting string
print(res)
Output
Hello, my name is Alice and I am 25 years old.
Explanation:
- F-strings allow embedding expressions directly inside string literals.
- We can access dictionary values using data['key'] syntax within the f-string.
Using Template Strings from string Module
The string.Template class provides another way to format strings using $ placeholders.
from string import Template
# Input string and dictionary
template = Template("Hello, my name is $name and I am $age years old.")
data = {'name': 'Alice', 'age': 25}
# Format the string
res = template.substitute(data)
# Resulting string
print(res)
Output
Hello, my name is Alice and I am 25 years old.
Explanation:
- Template class uses $key placeholders to insert dictionary values.
- substitute method replaces placeholders with corresponding dictionary values.