- String formatting — using % and format()
- f-strings — modern and concise formatting
- Pretty printing — using pprint for readable output
- JSON formatting — converting dictionaries to JSON
- Custom formatting — creating custom display formats
- Common mistakes — and how to avoid them
Introduction to Dictionary Formatting
Dictionary formatting refers to the process of displaying dictionary data in a readable, organized, or structured format. This is particularly useful for debugging, logging, generating reports, or preparing data for external systems.
Python provides several methods for formatting dictionaries:
- String formatting — using
%andformat() - f-strings — modern, concise, and readable
- Pretty printing — using
pprintmodule for structured display - JSON formatting — using
jsonmodule for serialization - Custom formatting — creating custom display formats
💡 Key concept: The right formatting method depends on your use case — debugging, logging, data exchange, or user presentation.
String Formatting
Using % and format()
Traditional string formatting methods can be used to format dictionary data into readable strings.
# Using % formatting (old style)
person = {"name": "Alice", "age": 25, "city": "NYC"}
print("Name: %(name)s, Age: %(age)d, City: %(city)s" % person)
# Name: Alice, Age: 25, City: NYC
# Using format() method
print("Name: {name}, Age: {age}, City: {city}".format(**person))
# Name: Alice, Age: 25, City: NYC
# Formatting with numbered placeholders
print("Name: {0[name]}, Age: {0[age]}, City: {0[city]}".format(person))
# Name: Alice, Age: 25, City: NYC
# Using format() with positional arguments
print("Name: {}, Age: {}, City: {}".format(person["name"], person["age"], person["city"]))
# Name: Alice, Age: 25, City: NYC
# Formatting multiple dictionaries
person1 = {"name": "Alice", "age": 25}
person2 = {"name": "Bob", "age": 30}
print("{name} is {age} years old".format(**person1))
print("{name} is {age} years old".format(**person2))
# Alice is 25 years old
# Bob is 30 years old
Characteristics:
- % formatting — old style, uses
%and%(key)s - format() — more modern, uses
{key}and**dict - Both are useful for simple formatting tasks
format()is more flexible and recommended
Quick Check: What does **dict do in format()? (Answer: It unpacks the dictionary into keyword arguments)
Using f-strings
Modern and Readable Formatting
f-strings (formatted string literals) provide the most concise and readable way to format dictionary data.
# Basic f-string formatting
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(f"Name: {person['name']}, Age: {person['age']}, City: {person['city']}")
# Name: Alice, Age: 25, City: NYC
# Accessing nested dictionary values
user = {
"name": "Alice",
"address": {"city": "NYC", "zip": "10001"}
}
print(f"Name: {user['name']}, City: {user['address']['city']}")
# Name: Alice, City: NYC
# Using expressions in f-strings
scores = {"math": 85, "science": 92, "english": 78}
print(f"Total: {sum(scores.values())}, Average: {sum(scores.values()) / len(scores):.2f}")
# Total: 255, Average: 85.00
# Formatting with f-string expressions
print(f"Name: {person['name'].upper()}, Age: {person['age'] + 1}")
# Name: ALICE, Age: 26
# Complex formatting
data = {"name": "Alice", "salary": 75000.50}
print(f"Name: {data['name']}, Salary: ${data['salary']:,.2f}")
# Name: Alice, Salary: $75,000.50
Characteristics:
- Most readable and concise
- Supports expressions inside
{} - Supports formatting specifiers (e.g.,
:,.2f) - Available in Python 3.6+
Quick Check: What is the syntax for f-strings? (Answer: f"text {expression}")
Pretty Printing (pprint)
Structured and Readable Display
The pprint module (pretty-print) provides a way to display dictionary data in a structured, readable format with proper indentation.
import pprint
# Basic pprint usage
person = {"name": "Alice", "age": 25, "city": "NYC", "hobbies": ["reading", "swimming", "coding"]}
pprint.pprint(person)
# {'age': 25,
# 'city': 'NYC',
# 'hobbies': ['reading', 'swimming', 'coding'],
# 'name': 'Alice'}
# Nested dictionaries
data = {
"user1": {"name": "Alice", "age": 25},
"user2": {"name": "Bob", "age": 30},
"user3": {"name": "Charlie", "age": 35}
}
pprint.pprint(data, indent=2)
# { 'user1': {'age': 25, 'name': 'Alice'},
# 'user2': {'age': 30, 'name': 'Bob'},
# 'user3': {'age': 35, 'name': 'Charlie'}}
# Customizing width and depth
pprint.pprint(data, width=40, indent=4)
# { 'user1': {'age': 25, 'name': 'Alice'},
# 'user2': {'age': 30, 'name': 'Bob'},
# 'user3': {'age': 35, 'name': 'Charlie'}}
# Using pprint in a script
pprint.pprint(data, sort_dicts=False) # Preserve insertion order
# Getting formatted string
formatted = pprint.pformat(data)
print(formatted)
Characteristics:
- Provides structured and readable output
- Supports indentation and width parameters
- Handles nested structures well
- Ideal for debugging and logging
Quick Check: What module is used for pretty printing? (Answer: pprint)
JSON Formatting
Converting Dictionaries to JSON
The json module provides methods to convert dictionaries to JSON format, which is useful for data exchange and storage.
import json
# Basic JSON conversion
person = {"name": "Alice", "age": 25, "city": "NYC"}
json_string = json.dumps(person)
print(json_string)
# {"name": "Alice", "age": 25, "city": "NYC"}
# Pretty-printed JSON
print(json.dumps(person, indent=4))
# {
# "name": "Alice",
# "age": 25,
# "city": "NYC"
# }
# Sorting keys in JSON
print(json.dumps(person, indent=2, sort_keys=True))
# {
# "age": 25,
# "city": "NYC",
# "name": "Alice"
# }
# Handling nested dictionaries
data = {
"user1": {"name": "Alice", "age": 25},
"user2": {"name": "Bob", "age": 30}
}
print(json.dumps(data, indent=2))
# {
# "user1": {
# "name": "Alice",
# "age": 25
# },
# "user2": {
# "name": "Bob",
# "age": 30
# }
# }
# Converting JSON back to dictionary
json_string = '{"name": "Alice", "age": 25}'
person = json.loads(json_string)
print(person) # {'name': 'Alice', 'age': 25}
Characteristics:
- json.dumps() — converts dict to JSON string
- json.loads() — converts JSON string to dict
- Supports indentation and sort_keys
- Ideal for data exchange and APIs
Quick Check: What method converts a dictionary to a JSON string? (Answer: json.dumps())
Custom Formatting
Creating Custom Display Formats
You can create custom formatting for dictionaries using loops, comprehensions, and string manipulation.
# Custom format using loop
person = {"name": "Alice", "age": 25, "city": "NYC"}
formatted = ""
for key, value in person.items():
formatted += f"{key}: {value}\n"
print(formatted)
# name: Alice
# age: 25
# city: NYC
# Using list comprehension
formatted = "\n".join([f"{key}: {value}" for key, value in person.items()])
print(formatted)
# Table format
data = [
{"name": "Alice", "age": 25, "city": "NYC"},
{"name": "Bob", "age": 30, "city": "LA"},
{"name": "Charlie", "age": 35, "city": "Chicago"}
]
print("Name | Age | City")
print("-" * 20)
for item in data:
print(f"{item['name']} | {item['age']} | {item['city']}")
# Custom formatting with separators
def format_dict(data, separator=", ", prefix="", suffix=""):
return prefix + separator.join([f"{k}: {v}" for k, v in data.items()]) + suffix
person = {"name": "Alice", "age": 25, "city": "NYC"}
print(format_dict(person, separator=" | ", prefix="[", suffix="]"))
# [name: Alice | age: 25 | city: NYC]
Methods:
- Loop-based — full control over formatting
- List comprehension — concise formatting
- Custom functions — reusable formatting logic
- Table format — aligning data in columns
Common Mistakes
Watch Out For These!
Mistake 1: Forgetting to Unpack in format()
# WRONG — treating dict as a single argument
person = {"name": "Alice", "age": 25}
# print("Name: {name}, Age: {age}".format(person)) # KeyError
# CORRECT — use ** to unpack
print("Name: {name}, Age: {age}".format(**person))
# Name: Alice, Age: 25
Mistake 2: Using f-strings in Older Python Versions
# WRONG — f-strings require Python 3.6+
person = {"name": "Alice", "age": 25}
# print(f"Name: {person['name']}") # SyntaxError in Python 3.5-
# CORRECT — use format() for compatibility
print("Name: {name}".format(**person))
Mistake 3: Not Handling Nested Structures in JSON
# WRONG — default JSON encoder may fail for some types
import json
person = {"name": "Alice", "age": 25, "hobbies": ["reading", "swimming"]}
json_string = json.dumps(person) # Works for basic types
# CORRECT — handle custom types with default parameter
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# person = Person("Alice", 25)
# json.dumps(person) # TypeError
# Use default parameter for custom objects
def serialize(obj):
if hasattr(obj, '__dict__'):
return obj.__dict__
raise TypeError(f"Object of type {type(obj)} is not JSON serializable")
# json_string = json.dumps(person, default=serialize)
Quick Check: What is the most common mistake when using format() with dictionaries? (Answer: Forgetting to use ** to unpack the dictionary)
Interactive Editor
Experiment with dictionary formatting techniques directly in your browser. Modify the code and see the results in real time.
DICTIONARY FORMATTING PRACTICE
========================================
Original: {'name': 'Alice', 'age': 25, 'city': 'NYC', 'hobbies': ['reading', 'swimming', 'coding']}
1. F-STRING FORMATTING
Name: Alice, Age: 25, City: NYC
2. FORMAT() METHOD
Name: Alice, Age: 25, City: NYC
3. PRETTY PRINTING
{ 'age': 25,
'city': 'NYC',
'hobbies': ['reading', 'swimming', 'coding'],
'name': 'Alice'}
4. JSON FORMATTING
{
"name": "Alice",
"age": 25,
"city": "NYC",
"hobbies": [
"reading",
"swimming",
"coding"
]
}
5. CUSTOM FORMATTING
name: Alice
age: 25
city: NYC
hobbies: ['reading', 'swimming', 'coding']
6. TABLE FORMAT
Name | Age | City
-------------------------
Alice | 25 | NYC
Bob | 30 | LA
Charlie | 35 | Chicago
Dictionary formatting practice complete!
Certificate of Completion
You have completed the Python Dictionary Formatting tutorial. You understand string formatting, f-strings, pprint, JSON formatting, and custom formatting techniques.
Quick Quiz — Test Your Knowledge
Let's see what you've learned about dictionary formatting:
**dict do in format()?Frequently Asked Questions
What is the difference between f-strings and format()?
{}. format() is more compatible with older Python versions and allows dynamic formatting strings.
When should I use pprint instead of print?
pprint when you need to display nested or complex dictionaries in a readable, structured format. It's especially useful for debugging and logging.
Can all Python objects be converted to JSON?
default parameter in json.dumps().
How do I format a dictionary as a table?
tabulate for advanced table formatting.
What is the default indentation in pprint?
pprint is 1 space. You can customize it using the indent parameter: pprint.pprint(data, indent=4).
Can I use f-strings with nested dictionaries?
f"{dict['key']['nested']}" or f"{dict.get('key', {}).get('nested')}" for safety.
Where to Go From Here
After mastering dictionary formatting, consider exploring these related topics:
Nested Dictionaries
Work with dictionaries within dictionaries.
Learn More →Dictionary Comprehension
Create dictionaries concisely using comprehension syntax.
Learn More →JSON Module
Learn more about working with JSON data in Python.
Learn More →