How to print a dictionary in Python
Learn to print a Python dictionary. You'll find different methods, tips, real-world applications, and solutions for common errors.

To print a Python dictionary is a fundamental task for developers who need to inspect data or debug code. Python’s built-in functions offer simple ways to display key-value pairs clearly.
In this article, you'll explore several techniques to print dictionaries. We'll cover practical tips, real-world applications, and advice to solve common errors to help you select the best method for your specific use case.
Basic printing with print()
my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict)--OUTPUT--{'name': 'John', 'age': 30, 'city': 'New York'}
Using the built-in print() function is the most direct way to display a dictionary's contents. It provides a raw, string-based representation of the key-value pairs, which is perfect for quick debugging or getting a snapshot of your data structure.
While simple, this method has its limits. The output isn't formatted for readability, so complex or nested dictionaries can appear as a dense, single line of text. This makes it less ideal for anything beyond basic inspection.
Basic dictionary printing methods
For more control over formatting and readability, you can move beyond the basic print() function and iterate through the dictionary in several more structured ways.
Iterating through keys with a for loop
person = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in person:
print(f"{key}: {person[key]}")--OUTPUT--name: John
age: 30
city: New York
Iterating with a for loop gives you more control over the output. By default, when you loop directly over a dictionary, you're actually iterating through its keys.
Inside the loop, you can use each key to access its corresponding value using standard bracket notation, like person[key]. This approach allows you to:
- Format each key-value pair on a new line.
- Add custom text or logic for each item.
Using the items() method for key-value pairs
person = {'name': 'John', 'age': 30, 'city': 'New York'}
for key, value in person.items():
print(key, "->", value)--OUTPUT--name -> John
age -> 30
city -> New York
The items() method offers a more Pythonic way to loop through a dictionary. It returns key-value pairs together, allowing you to unpack them directly into two variables—like key and value in the example. This approach is often preferred for its clarity and efficiency.
- It’s more readable because it explicitly states you’re working with both the key and its corresponding value.
- You get direct access to both elements without needing an extra lookup like
person[key]inside the loop.
String formatting with dictionary unpacking
person = {'name': 'John', 'age': 30, 'city': 'New York'}
print("Person: {name}, {age} years old, from {city}".format(**person))--OUTPUT--Person: John, 30 years old, from New York
You can directly embed a dictionary into a string using the ** operator for unpacking. This operator passes the dictionary's key-value pairs as keyword arguments to the .format() method. The placeholders in your string, like {name}, are then automatically filled with the corresponding values.
- This approach is incredibly clean for creating formatted output from a dictionary.
- It requires that the placeholder names in the string exactly match the keys in your dictionary.
Advanced dictionary printing techniques
When basic iteration isn't enough for complex or nested dictionaries, you can turn to specialized tools designed for creating clean, structured, and human-readable output.
Pretty printing with the pprint module
from pprint import pprint
nested_dict = {'person': {'name': 'John', 'age': 30},
'location': {'city': 'New York', 'country': 'USA'}}
pprint(nested_dict, width=40)--OUTPUT--{'location': {'city': 'New York',
'country': 'USA'},
'person': {'age': 30, 'name': 'John'}}
The pprint module is your go-to for making complex data structures readable. It's built specifically for "pretty-printing" things like nested dictionaries, automatically adding indentation and line breaks to clarify the structure where a simple print() would fail.
- It intelligently formats nested items, making the hierarchy easy to follow.
- By default, it sorts keys alphabetically, which helps create consistent and predictable output for easier comparison.
- You can customize the layout, like using the
widthparameter to control the maximum line length.
JSON formatting for readable output
import json
person = {'name': 'John', 'age': 30, 'city': 'New York'}
formatted_dict = json.dumps(person, indent=4)
print(formatted_dict)--OUTPUT--{
"name": "John",
"age": 30,
"city": "New York"
}
The json module offers a powerful way to format dictionaries, especially if you're preparing data for logging or an API. The json.dumps() function converts your dictionary into a JSON-formatted string—a universal standard for data exchange.
- The magic happens with the
indentparameter. Settingindent=4tells the function to format the output with four-space indentation, making it highly readable. - This method is not just for web development; it's a fantastic general-purpose tool for visualizing any dictionary structure clearly.
Custom alignment and formatting for tabular display
inventory = {'apple': 10, 'banana': 15, 'orange': 8, 'grape': 25}
print("Inventory:")
for item, quantity in inventory.items():
print(f"{item.ljust(10)} : {quantity:3d} units")--OUTPUT--Inventory:
apple : 10 units
banana : 15 units
orange : 8 units
grape : 25 units
For a clean, tabular look, you can combine f-strings with string formatting methods. This gives you precise control over alignment without needing a special library. It’s perfect for creating simple reports or neatly organized logs directly from your dictionary data.
- The
ljust()method pads a string with spaces on the right, making it a specific length. This effectively left-aligns the text. - In the f-string,
{quantity:3d}formats the number to take up three characters, adding padding on the left to right-align the values.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the dictionary printing techniques we've explored, Replit Agent can turn them into production-ready tools:
- Build a configuration file generator that uses
json.dumps()to create clean, indented settings files. - Create a command-line inventory tracker that displays stock levels in a neat, tabular format using f-strings and custom alignment.
- Deploy a debugging utility that visualizes complex, nested data structures from an API response with
pprint.
Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
When printing dictionaries, you might run into a few common roadblocks, but they're easy to navigate with the right approach.
A KeyError is one of the most frequent issues you'll face. It happens when you try to access a key that isn't in the dictionary, causing your program to crash if it isn't handled. For example, trying to get a value with bracket notation for a key that doesn't exist will raise this error immediately.
To avoid a KeyError, you can use the dictionary's get() method. Instead of raising an error, get() returns None if a key is missing. You can also provide a default value—like person.get('job', 'Not specified')—which gives you a safe way to handle potentially missing data without interrupting your code's flow.
You might also encounter a TypeError if your dictionary contains values of different data types. This often happens during string formatting if you try to apply a number-specific format to a string value, or vice-versa. To fix this, you can either ensure your data is consistent or add logic to check the type of each value before you try to print it.
Handling KeyError when accessing non-existent keys
When you directly access a dictionary value using bracket notation, you're assuming the key exists. If it doesn't, Python immediately raises a KeyError, which can crash your script if you haven't planned for it.
For instance, the code below attempts to print a user's phone number, but the 'phone' key is missing from the user_data dictionary, triggering the error.
user_data = {'name': 'Alice', 'email': 'alice@example.com'}
print(f"User: {user_data['name']}, Phone: {user_data['phone']}")
The f-string attempts to access the 'phone' key, which isn't present in the dictionary, causing the KeyError. The following example shows a safer way to retrieve values that might be missing without causing a crash.
user_data = {'name': 'Alice', 'email': 'alice@example.com'}
if 'phone' in user_data:
print(f"User: {user_data['name']}, Phone: {user_data['phone']}")
else:
print(f"User: {user_data['name']}, Phone: Not provided")
To prevent a KeyError, you can check if a key exists before trying to use it. The code uses the in operator to see if the 'phone' key is in the user_data dictionary. If it’s there, the code prints the value; otherwise, it prints a fallback message. This conditional check is a robust way to handle potentially missing data, especially when working with external sources like APIs where certain fields might be optional.
Using the get() method to handle missing keys
The get() method offers a more concise way to handle missing keys than an if check. It safely retrieves a value, returning None or a default if the key is absent, preventing a KeyError. The code below fails because it doesn't use this safeguard.
preferences = {'theme': 'dark', 'font_size': 14}
print(f"Language: {preferences['language']}, Theme: {preferences['theme']}")
The f-string attempts to access the 'language' key, but it isn't defined in the preferences dictionary, which causes an error. The following example shows how to handle this safely.
preferences = {'theme': 'dark', 'font_size': 14}
print(f"Language: {preferences.get('language', 'default')}, Theme: {preferences['theme']}")
The get() method offers a clean fix. In the code, preferences.get('language', 'default') searches for the 'language' key. Because the key is missing, the method returns the provided default value, 'default', instead of raising an error. This approach is perfect for handling optional dictionary keys, like those from API responses or configuration files, ensuring your code runs smoothly even with incomplete data.
Dealing with TypeError when printing dictionaries with mixed types
A TypeError often appears when your dictionary holds mixed data types, like strings, integers, and None. You'll trigger this error if you try an operation, such as addition with the + operator, on values that aren't compatible. The following code illustrates this problem.
metrics = {'views': '1500', 'likes': '300', 'shares': None}
total = metrics['views'] + metrics['likes'] + metrics['shares']
print(f"Total engagement: {total}")
This code triggers a TypeError because the + operator can't be used between a string and a None value. The values in the metrics dictionary are incompatible. The next example shows a safe way to proceed.
metrics = {'views': '1500', 'likes': '300', 'shares': None}
views = int(metrics['views']) if metrics['views'] else 0
likes = int(metrics['likes']) if metrics['likes'] else 0
shares = int(metrics['shares']) if metrics['shares'] else 0
total = views + likes + shares
print(f"Total engagement: {total}")
To fix the TypeError, the solution ensures all values are integers before performing addition. It uses a conditional expression to check each value; if a value exists, it’s converted using int(), but if it's None or empty, it defaults to 0. This prevents the error that happens when you try to use the + operator on incompatible types. You'll often encounter this when processing data from APIs or databases where types can be inconsistent.
Real-world applications
Now that you can print dictionaries and handle common errors, you can apply these skills to build practical, real-world applications.
Displaying user settings with status indicators
Iterating through a settings dictionary is a great way to build a dynamic status display, allowing you to translate boolean values like True and False into more intuitive visual indicators.
user_settings = {
'notifications': True,
'dark_mode': False,
'auto_save': True,
'sharing': False
}
for setting, enabled in user_settings.items():
status = "✓" if enabled else "✗"
print(f"{setting.replace('_', ' ').title()}: {status}")
This example combines several techniques to create a clean summary from a settings dictionary.
- The loop iterates over key-value pairs directly using
.items(), which is both efficient and readable. - A compact conditional expression translates each boolean value into a status symbol—a checkmark for
Trueor an 'X' forFalse. - String methods like
.replace()and.title()are chained to format the dictionary keys into polished labels, turning a key likedark_modeinto "Dark Mode".
This approach is great for presenting configuration data in a clear, human-readable way.
Creating a mini dashboard from website analytics data
Dictionary printing is also ideal for creating simple reports, like turning raw website analytics into a formatted, easy-to-read dashboard.
analytics = {
'visitors': 12500,
'page_views': 48700,
'bounce_rate': 0.35,
'avg_time': 127,
'conversion': 0.063
}
print("WEBSITE ANALYTICS DASHBOARD")
print(f"Visitors: {analytics['visitors']:,}")
print(f"Page Views: {analytics['page_views']:,}")
print(f"Bounce Rate: {analytics['bounce_rate']:.1%}")
print(f"Avg. Time on Site: {analytics['avg_time'] // 60}m {analytics['avg_time'] % 60}s")
print(f"Conversion Rate: {analytics['conversion']:.2%}")
This example showcases how you can use f-strings to create a formatted report directly from a dictionary. It leverages powerful, built-in format specifiers to present raw numbers in a more human-readable way without extra logic.
- The
:,specifier automatically adds thousand separators to large integers. - The
:.1%specifier converts a float to a percentage and rounds it to one decimal place. - Integer division (
//) and the modulo operator (%) work together to cleanly convert a total number of seconds into a minutes-and-seconds format.
Get started with Replit
Turn your new skills into a real tool. Describe your idea to Replit Agent, like “build a JSON pretty-printer” or “create a command-line tool to display inventory data in a formatted table.”
The agent writes the code, tests for errors, and deploys your app from a single prompt. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.



%2520in%2520Python.png)