Skip to main content

How to Pass a Dictionary into `str.format()` in Python

How to Pass a Dictionary into str.format() in Python

In Python, the str.format() method allows us to insert values into a string by using placeholders. These placeholders are represented by curly braces {} and can be replaced with the desired values. We can pass a dictionary as an argument to str.format() to replace multiple placeholders with key-value pairs from the dictionary.

Here's a step-by-step tutorial on how to pass a dictionary into str.format() in Python:

Step 1: Create a Dictionary​

First, create a dictionary with the values you want to insert into the string. The dictionary should consist of key-value pairs, where the keys represent the placeholders in the string.

data = {
'name': 'John',
'age': 25,
'country': 'USA'
}

In this example, we have a dictionary called data with three keys: 'name', 'age', and 'country'.

Step 2: Define the String​

Next, define the string where you want to insert the values from the dictionary. Placeholders for the dictionary keys should be included using curly braces {}.

message = "My name is {name}, I am {age} years old, and I live in {country}."

We have defined a string called message with three placeholders: {name}, {age}, and {country}.

Step 3: Pass the Dictionary into str.format()​

To pass the dictionary into str.format(), call the format() method on the string and pass the dictionary as an argument.

formatted_message = message.format(**data)

The **data syntax is used to unpack the dictionary and pass its key-value pairs as keyword arguments to the format() method.

Step 4: Print or Use the Formatted String​

Finally, you can print or use the formatted string as desired. The placeholders in the string will be replaced with the corresponding values from the dictionary.

print(formatted_message)

The output will be:

My name is John, I am 25 years old, and I live in USA.

Additional Examples​

Example 1: Numeric Values​

data = {
'num1': 10,
'num2': 5,
'sum': 15
}

message = "The sum of {num1} and {num2} is {sum}."

formatted_message = message.format(**data)
print(formatted_message)

Output:

The sum of 10 and 5 is 15.

Example 2: Date Values​

data = {
'day': 12,
'month': 'October',
'year': 2022
}

message = "Today is {day}th {month}, {year}."

formatted_message = message.format(**data)
print(formatted_message)

Output:

Today is 12th October, 2022.

Example 3: Boolean Values​

data = {
'is_sunny': True,
'is_rainy': False
}

message = "Is it sunny? {is_sunny}. Is it rainy? {is_rainy}."

formatted_message = message.format(**data)
print(formatted_message)

Output:

Is it sunny? True. Is it rainy? False.

By following these steps and examples, you can easily pass a dictionary into str.format() in Python and dynamically insert values into your strings.