Python

P
PythonHub
Progress 0%

Python

  • Home
  • History of Python
  • Applications of Python
  • Introduction To Python
    • What is Python
    • Character Set
    • Tokens in Python
    • Python Execution Mode
    • Variable And Identifiers
    • Data Types in Python
    • Operators And Expressions
    • Constants in Python
    • Assignment Statement
    • Input / Output in Python
    • Simple Python Scripts
    • Namespace in Python
    • 📝 Assignments
  • Operators in Python
    • Arithmetic Operators
    • Assignment Operators
    • Shorthand Assignment Operators
    • Relational Operators
    • Logical Operators
    • Bitwise Operators
    • Special Operators
    • 📝 Assignments
  • Input Output in Python
    • Accept Input
    • Output Formatting
    • 📝 Assignments
  • Conditional Statement
    • Decision Making
    • if Statement
    • IF-ELSE STATEMENT
    • IF-ELSE LADDER
    • NESTED IF-ELSE
    • Short Hand IF-ELSE
    • 📝 Assignments
  • Loops
    • Introduction to Loops
    • While Loop
    • Nested While Loop
    • 📝 While Loop Assignments
    • For Loop
    • For Loop Examples
    • Nested For Loop
    • Nested For Loop Examples
    • Infinite While Loops
    • Infinite For Loops
    • Break, Continue and Else in Loops
    • Difference Between For and While Loop
    • For Each Loop
    • 📝 For Each Assignments
    • 📝 All Loops Assignments
  • List
    • List in Python
    • Access List Elements
    • List Functions
    • Iterate (Loop) List
    • List Comprehension
    • 📝 Assignments
  • Tuple
    • Tuple in Python
    • Access Tuple Elements
    • Tuple Functions
    • Iterate (Loop) Tuple
    • Unpack Tuple
    • Tuple Comprehension
    • 📝 Assignments
  • Set
    • Set in Python
    • Access Set Elements
    • Set Methods
    • Iterate (Loop) Set
    • Pack/Unpack Set
    • Set Comprehension
    • 📝 Assignments
  • Dictionary
    • Dictionary
    • Access Dictionary Items
    • Dictionary Methods
    • Iterate (Loop) Dictionary
    • Formatting Dictionaries
    • Nested Dictionaries
    • Dictionary Comprehension
    • 📝 Assignments
  • Diff List Tuple Set Dictionary
    • List vs Tuple
    • List vs Set
    • List vs Dictionary
    • Tuple vs Set
    • Tuple vs Dictionary
    • Dictionary vs Set
    • 📝 Assignments
  • Exception
    • Error vs Exception
    • Exception Handling
    • Types of Exception
    • User Defined Exception
    • Logging Exception
    • 📝 Assignments
  • Functions
    • Introduction to Functions
    • Modular Programming
    • Types of Functions
    • Inbuilt Functions
    • Need For User-Defined Function
    • Elements of User Defined Function
    • Function Arguments
    • Nesting of Functions
    • Recursion
    • Global Local and Non Local
    • Python Lambda Functions
    • 📝 Assignments
  • Python Module
    • Introduction to Module
    • Inbuilt Modules in Python
    • User Defined Module
    • 📝 Assignments
  • File Handling
    • Introduction to Files
    • Create File
    • Read Files
    • Write to File
    • Rename File
    • Copy File
    • Move File
    • List Files in Directory
    • Binary Files
    • Zipping and Unzipping Files
    • 📝 Assignments
  • Strings
    • Basics of Strings
    • String Special Operators
    • String Formatting Operators
    • String Methods
    • 📝 Assignments
  • Regular Expressions
  • Python OOPS
    • Basics of Object Oriented
    • What are Classes and Objects?
    • Creating Class and Object
    • OOP vs Procedural Programming
    • Difference Between Classes and Objects
    • Constructors
    • Destructor
    • Built Class Methods and Attributes
    • Class and Instance Variables
    • Inheritance in Python
    • Single Inheritance
    • Multiple Inheritance
    • Multilevel Inheritance
    • Hierarchical Inheritance
    • Hybrid Inheritance
    • Abstraction
    • Method Overriding
    • Abstract Method
    • Interfaces in Python
    • Abstract Class vs Interface
    • Public, Private and Protected
    • Overloading vs Overriding
    • Inheritance vs Composition
    • Encapsulation
    • Polymorphism
    • Inner Classes
    • 📝 Assignments
  • Advanced Python
    • Iterator in Python
    • Generator in Python
    • Decorator in Python
    • Type Hints in Python
    • Async/Await Programming
    • Dataclasses in Python
    • Context Managers in Python
    • Property Decorator in Python
    • __slots__ in Python
    • Enums in Python
    • Walrus Operator in Python
    • Match-Case in Python
    • 📝 Assignments
  • Python Standard Library
    • Collections Module
    • Itertools Module
    • Functools Module
    • Datetime Module
    • JSON Module
    • OS Module
    • Sys Module
    • Random Module
    • Math Module
    • 📝 Assignments
  • Python Testing
    • Unit Testing in Python
    • Pytest Framework
    • Mocking in Python
    • 📝 Assignments
  • Python Best Practices
    • PEP 8 Style Guide
    • Docstrings in Python
    • Logging in Python
    • Code Optimization Tips
    • Debugging Techniques
    • 📝 Assignments
  • MySQL Database in Python
    • Introduction to MySQL with Python
    • DBMS vs File System
    • Connecting to MySQL Database
    • Create Database in MySQL
    • Create Table in MySQL
    • Insert Data in MySQL
    • Insert Multiple Rows
    • Select Data from MySQL
    • WHERE Clause in MySQL
    • Update Data in MySQL
    • Delete Data from MySQL
    • Parameterized Queries
    • Transaction Management
    • Error Handling
    • Connection Pooling
    • MySQL Drivers Guide
    • Joins in MySQL
    • Aggregation Functions
    • Backup MySQL Database
    • Best Practices
    • 📝 Assignments
  • MySQL Database Operations
    • SELECT Statement
    • MySQL Operators
    • DDL Statements
    • DML Statements
    • Subqueries
    • JOIN Operations
    • Aggregation
    • Case Study
    • 📝 Assignments
  • Graphics in Python
  • Threads in Python
    • Introduction to Threads
    • Process vs Threads
    • Concurrent Programming & GIL
    • Uses of Threads
    • Creating Threads
    • Single Tasking
    • Multi Tasking
    • Thread Synchronization
    • 📝 Assignments
  • Interview Questions & Answers
  • Python Case Studies
  • Multiple Choice Questions
  • 📝 Practice Problems
Get in Touch
  • tech2dsm@gmail.com

© Sankalan Data Tech

Python Language Interactive Tutorial

Python Dictionary: Formatting

Python Dictionary Formatting - Complete Guide

Learn how to format and display Python dictionaries using string formatting, pprint, and JSON.

Created by Sankalan Data Tech Team Verified
Data Engineers, Analysts, Scientists & Trainers
Created by experienced Python developers, data engineers, and data scientists to make programming easy through practical examples, real-world experience, and clear explanations.
On this page:
  • Introduction to Dictionary Formatting
  • String Formatting
  • Using f-strings
  • Pretty Printing (pprint)
  • JSON Formatting
  • Custom Formatting
  • Common Mistakes
  • Interactive Editor
  • Quiz
  • FAQ
Share this tutorial:
Twitter LinkedIn Facebook WhatsApp Reddit Telegram Email Copy Link
What You Will Learn
  • 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 % and format()
  • f-strings — modern, concise, and readable
  • Pretty printing — using pprint module for structured display
  • JSON formatting — using json module 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

1

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

2

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)

3

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

4

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

5

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

6

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.

Loading Pyodide... 0%
Python Code Editor
========================================
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:

1. What is the syntax for f-strings in Python?
2. Which module is used for pretty printing dictionaries?
3. How do you convert a dictionary to a JSON string?
4. What does **dict do in format()?
5. Which method is most readable and concise for formatting dictionaries?

Frequently Asked Questions

What is the difference between f-strings and format()? ▼

f-strings are more concise and readable, allowing expressions inside {}. format() is more compatible with older Python versions and allows dynamic formatting strings.

When should I use pprint instead of print? ▼

Use 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? ▼

Only basic types (dict, list, str, int, float, bool, None) are JSON-serializable. Custom objects require a custom encoder or the default parameter in json.dumps().

How do I format a dictionary as a table? ▼

Use a loop to iterate over the dictionary and print each key-value pair in columns. You can also use libraries like tabulate for advanced table formatting.

What is the default indentation in pprint? ▼

The default indentation in 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? ▼

Yes, you can access nested dictionary values using 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 →
Interview Resources
  • Python Syntax & Variables Interview Questions
  • Top SQL Interview Questions & Answers
  • SQL Joins: Displaying Data from Multiple Tables FAQ
  • Top PL SQL Interview Questions
Previous: Iterate Dictionary Next: Nested Dictionaries →