How to print a dictionary in Python

Learn how to print a dictionary in Python. Explore various methods, tips, real-world uses, and how to debug common errors.

How to print a dictionary in Python
Published on: 
Fri
Feb 13, 2026
Updated on: 
Mon
Apr 13, 2026
The Replit Team

Python dictionaries are a core data structure, and you'll often need to print their contents to debug code or display data. Python provides several straightforward methods to view these key-value pairs effectively.

In this article, we'll explore various techniques to print dictionaries. You'll find practical tips, see real-world applications, and get advice to debug common issues, helping you handle dictionary output with confidence.

Basic printing with print()

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}
print(my_dict)--OUTPUT--{'name': 'John', 'age': 30, 'city': 'New York'}

The most direct way to view a dictionary is by passing it to the print() function. This approach is perfect for quick debugging or getting a simple snapshot of your data. When you print a dictionary, Python implicitly calls its __str__() method, which generates a string representation of the object.

The output mirrors the dictionary's literal syntax, showing all key-value pairs enclosed in curly braces. While this is great for a quick look, it doesn't offer much control over formatting for more complex or user-facing output.

Basic dictionary printing methods

For more refined control over how your dictionary is displayed, you can iterate through its contents and format the output to your exact specifications.

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

Looping directly over a dictionary with a for loop is a common and intuitive way to access its contents. By default, this iteration gives you each key one by one. Inside the loop, you can then use the key to retrieve its corresponding value using standard bracket notation, like person[key], following the same principles as accessing dictionary values.

  • This method gives you full control over the output format.
  • Using an f-string, as shown in the example, lets you easily structure each line to display the key and value clearly.

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

For a more direct approach, the items() method lets you access both the key and its corresponding value in each loop iteration. It returns a view of key-value pairs, which you can unpack directly into two variables like key and value. This technique is fundamental to looping through dictionaries effectively.

  • This is often more efficient since you don't need an extra lookup step to get the value.
  • It also makes your code more readable, as your intent to use both key and value is clear from the start.

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 also format strings directly using dictionary unpacking. The double-asterisk operator ** in .format(**person) unpacks the dictionary, passing its key-value pairs as keyword arguments to the method. The placeholders in the string, like {name}, are then matched with the corresponding dictionary keys.

  • This technique is incredibly concise, especially when your string template's placeholders already match your dictionary keys.
  • It's a powerful way to populate text templates without needing a loop, making your code cleaner and more readable.

Advanced dictionary printing techniques

When your dictionaries become large or nested, simple printing isn't enough—you'll need more advanced techniques to format the output for clarity and structure.

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'}}

Python's built-in pprint module is your go-to for making complex data structures readable. It automatically formats nested dictionaries with indentation and line breaks, so you don't have to squint at a long, jumbled line of text. This is especially useful for debugging.

  • It sorts the dictionary keys alphabetically before printing, which provides a consistent and predictable output.
  • You can control the layout with parameters like width, which sets the maximum number of characters per line.

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 provides a powerful way to format dictionaries for readability. Using the json.dumps() function, you can convert a dictionary into a JSON-formatted string. The real magic for clean output comes from the indent parameter. For more details on converting dictionaries to JSON, this approach offers excellent formatting control.

  • Setting indent=4 tells the function to use four spaces for each level of nesting, which creates a structured and easy-to-read layout.
  • This method is perfect when you need output that's easy for humans to parse, like in configuration files or API responses.

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 a for loop with advanced f-string formatting. This gives you precise control over alignment and spacing, making your dictionary output much easier to read, especially when presenting data like an inventory list.

  • The ljust(10) method pads the item string with spaces on the right, aligning all the colons vertically.
  • The :3d format specifier formats the quantity as a decimal integer (d) within a 3-character space, which right-aligns the numbers.

Move faster with Replit

Replit is an AI-powered development platform that comes with all Python dependencies pre-installed, so you can skip setup and start coding instantly. This lets you move directly from learning individual techniques, like the dictionary printing methods we've covered, to building complete applications.

With Agent 4, you can describe the app you want to build, and it will take your idea to a working product. For example, you could ask it to create:

  • A configuration file generator that takes a dictionary of settings and formats it into a clean, human-readable text file using custom alignment.
  • An API data simulator that converts a nested Python dictionary into a properly indented JSON structure for testing frontend applications.
  • An inventory reporting tool that iterates through a product dictionary and prints a formatted, tabular report of item names and stock quantities.

Simply describe your app, and Replit will write the code, test it, and fix issues automatically, all within your browser.

Common errors and challenges

While printing dictionaries is usually straightforward, you might encounter a few common errors, but they're simple to solve with the right approach or automated code repair.

Handling KeyError when accessing non-existent keys

One of the most common issues is the KeyError. This error pops up when you try to access a dictionary key that doesn't exist using bracket notation. For instance, if your code tries to retrieve a key that isn't in the dictionary, your program will stop and raise this error. For comprehensive strategies on solving KeyError exceptions, there are multiple approaches to handle missing keys gracefully.

Using the get() method to handle missing keys

To avoid this, you can use the get() method. It's a safer way to access keys because it won't crash your program if a key is missing—instead, it simply returns None. You can also provide a default value as a second argument. For example, person.get('job', 'Unemployed') would return 'Unemployed' if the 'job' key isn't found, which is perfect for making your code more resilient.

Dealing with TypeError when printing dictionaries with mixed types

Another potential hurdle is the TypeError. This often happens when you try to combine strings with other data types, like numbers, using the + operator. An expression like 'Age: ' + person['age'] will fail if the age is an integer. The fix is to ensure all parts of the string are actually strings. You can explicitly convert values using the str() function, or even better, use f-strings like f"Age: {person['age']}", which handle the conversion for you automatically.

Handling KeyError when accessing non-existent keys

This error often happens when your code assumes a key exists. For instance, trying to access a 'phone' key from user data that only contains a name and email will cause a crash. The following code demonstrates this exact scenario.

user_data = {'name': 'Alice', 'email': 'alice@example.com'}
print(f"User: {user_data['name']}, Phone: {user_data['phone']}")

This code fails because it tries to access the 'phone' key directly, but that key doesn't exist in the user_data dictionary. The following example shows how to handle this gracefully.

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 first verify if a key exists using the in keyword. The code checks if 'phone' is in user_data before attempting to access its value. If the key is missing, the else block provides a fallback, preventing a crash. This approach is essential when dealing with unpredictable data structures, like API responses or user-submitted forms, where certain fields might not always be present.

Using the get() method to handle missing keys

The get() method provides a more elegant solution for missing keys. It's a concise alternative to an if-else block, letting you specify a default value in one line. This keeps your code cleaner and more resilient. The following code demonstrates the error-prone approach.

preferences = {'theme': 'dark', 'font_size': 14}
print(f"Language: {preferences['language']}, Theme: {preferences['theme']}")

This code fails because it directly accesses the language key, which isn't defined in the dictionary, causing a program-stopping KeyError. The following example shows a much safer way to retrieve this value without causing a crash.

preferences = {'theme': 'dark', 'font_size': 14}
print(f"Language: {preferences.get('language', 'default')}, Theme: {preferences['theme']}")

By using preferences.get('language', 'default'), the code safely retrieves a value without causing an error. Since the 'language' key is missing, the get() method returns the specified default, 'default', instead of crashing the program. This makes your code more robust, especially when working with dictionaries where some keys might be optional, like configuration files or API results.

Dealing with TypeError when printing dictionaries with mixed types

Dealing with TypeError when printing dictionaries with mixed types

A TypeError is a common roadblock that occurs when you try an operation on incompatible data types. You can't, for example, use the + operator on a string and a None type. The following code fails for this exact reason.

metrics = {'views': '1500', 'likes': '300', 'shares': None}
total = metrics['views'] + metrics['likes'] + metrics['shares']
print(f"Total engagement: {total}")

The issue arises because the value for 'shares' is None. Trying to add this to the string values for 'views' and 'likes' with the + operator causes a TypeError. The following example shows how to handle this correctly.

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}")

The solution prevents a TypeError by converting all values to a common, numeric type before performing addition. It uses a conditional expression to safely cast each value to an integer with int(), defaulting to 0 if a value is missing or None. This ensures all items can be added together mathematically. You'll find this approach crucial when processing data from external sources like APIs, where data types can be inconsistent or values might be absent. Understanding the fundamentals of creating Python dictionaries helps ensure proper data structure setup from the beginning.

Real-world applications

Beyond debugging, these printing techniques are fundamental for creating user-facing features like status displays and simple analytics dashboards.

Displaying user settings with status indicators

This technique is perfect for creating a user-friendly settings page, where you can loop through a dictionary and translate boolean values into clear 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 code snippet demonstrates how to transform raw dictionary data into a formatted, readable list. It iterates through the user_settings dictionary, unpacking each key-value pair with the .items() method.

  • A ternary operator—"✓" if enabled else "✗"—concisely converts the boolean value into a status symbol.
  • The f-string in the print() function uses .replace('_', ' ').title() to clean up the setting's key, turning something like 'dark_mode' into 'Dark Mode'.

The result is a clean output that combines the formatted key with its corresponding status symbol.

Creating a mini dashboard from website analytics data

You can also use f-string formatting to present different data types from a dictionary, such as numbers, percentages, and time, in a clean and readable summary.

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 snippet showcases how f-strings can create a polished, readable summary from a dictionary. It accesses values from the analytics dictionary and applies specific formatting to each one.

  • The :, format specifier adds comma separators to large numbers like visitors.
  • :.1% converts decimal values like bounce_rate into percentages with one decimal place.
  • Simple math with // and % operators transforms the total seconds for avg_time into a clear minutes-and-seconds format.

This approach is great for building simple reports or dashboards directly in your terminal, or you could expand it into a full web dashboard using vibe coding.

Get started with Replit

Put these printing methods to work by building a real tool. Just tell Replit Agent to “create a script that formats analytics data into a dashboard” or “build a config file viewer that pretty-prints a dictionary.”

It will write the code, test for errors, and deploy the app for you. All you need is an idea. Start building with Replit.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.

Build your first app today

Describe what you want to build, and Replit Agent writes the code, handles the infrastructure, and ships it live. Go from idea to real product, all in your browser.