Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How do I format a string using a dictionary in Python 3?
You can use dictionaries to format strings in Python using several methods. The most common approaches are %-formatting, str.format(), and f-strings. Each method allows you to insert dictionary values into string templates.
Using %-formatting with Dictionaries
The traditional method uses % operator with dictionary keys in parentheses ?
data = {'language': 'Python', 'number': 2, 'cost': 99.99}
# Basic string interpolation
result = '%(language)s has %(number)03d quote types.' % data
print(result)
# Formatting numbers
price = 'The course costs $%(cost).2f' % data
print(price)
Python has 002 quote types. The course costs $99.99
Using str.format() with Dictionaries
The str.format() method provides more flexibility and readability ?
data = {'name': 'Alice', 'age': 30, 'score': 95.7}
# Using dictionary unpacking
result = "Name: {name}, Age: {age}, Score: {score:.1f}".format(**data)
print(result)
# Direct dictionary access
result2 = "Hello {0[name]}, you scored {0[score]:.2f}%".format(data)
print(result2)
Name: Alice, Age: 30, Score: 95.7 Hello Alice, you scored 95.70%
Using f-strings (Recommended)
F-strings (Python 3.6+) offer the cleanest and most readable syntax ?
data = {'product': 'Laptop', 'price': 1299.99, 'quantity': 5}
# Direct dictionary access in f-strings
result = f"Product: {data['product']}, Price: ${data['price']:.2f}"
print(result)
# Multiple values
summary = f"Order: {data['quantity']} x {data['product']} = ${data['price'] * data['quantity']:.2f}"
print(summary)
Product: Laptop, Price: $1299.99 Order: 5 x Laptop = $6499.95
Comparison
| Method | Syntax | Python Version | Performance |
|---|---|---|---|
| %-formatting | '%(key)s' % dict |
All versions | Slower |
| str.format() | '{key}'.format(**dict) |
2.7+ | Medium |
| f-strings | f"{dict['key']}" |
3.6+ | Fastest |
Conclusion
Use f-strings for modern Python code as they're fastest and most readable. Use str.format() for older Python versions or complex formatting needs. The % operator is legacy but still widely supported.
Advertisements
