Table of contents
Implement code functionality

How to print a dictionary in Python

May 30, 2025
 ・ by  
Claude and the Anthropic Team
Table of contents
H2 Link Template
Try Claude

Dictionaries in Python store key-value pairs that let you organize and access data efficiently. Understanding how to print dictionaries properly helps you debug code, analyze data structures, and create readable program output.

This guide covers essential dictionary printing techniques, with practical tips and real-world examples. All code samples were developed with Claude, an AI assistant built by Anthropic.

Basic printing with print()

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

The print() function displays dictionaries in a straightforward key-value format, making it ideal for quick debugging and data inspection. When you pass a dictionary directly to print(), Python automatically converts it to a string representation that preserves the dictionary's structure.

This basic printing method offers several advantages for developers:

  • Maintains the exact structure of nested data
  • Shows the data types of values through quotation marks and formatting
  • Requires no additional imports or configuration

While simple, this approach works best for small dictionaries or initial debugging. The output becomes harder to read with larger or more complex dictionary structures.

Basic dictionary printing methods

Python offers several methods beyond basic print() to display dictionaries more elegantly and extract specific information you need for your programs.

Iterating through keys with a for loop

person = {'name': 'John', 'age': 30, 'city': 'New York'}
for key in person:
    print(f"{key}: {person[key]}")
name: John
age: 30
city: New York

The for loop provides a clean way to display each key-value pair on its own line. Python automatically iterates through dictionary keys, letting you access corresponding values using square bracket notation person[key].

  • Each iteration prints one key-value pair using an f-string, creating a vertical list format that's easier to read than the default dictionary output
  • This method gives you more control over formatting compared to basic print()
  • You can easily modify the output format by changing the f-string template

The vertical format makes the dictionary's contents more scannable, especially when working with larger data structures or when you need to present the information to other developers.

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)
name -> John
age -> 30
city -> New York

The items() method provides a more elegant way to access both keys and values simultaneously. It returns key-value pairs that you can directly unpack in a for loop, eliminating the need for bracket notation.

  • The syntax for key, value in person.items() automatically unpacks each pair into separate variables
  • This approach makes the code more readable and reduces the chance of errors when accessing dictionary values
  • You can name the loop variables anything meaningful—not just "key" and "value"

The arrow operator -> in the print statement creates a clear visual separation between keys and values. This formatting choice makes the output particularly useful when reviewing dictionary contents during development or debugging sessions.

String formatting with dictionary unpacking

person = {'name': 'John', 'age': 30, 'city': 'New York'}
print("Person: {name}, {age} years old, from {city}".format(**person))
Person: John, 30 years old, from New York

Dictionary unpacking with the double asterisk operator (**) automatically maps dictionary keys to their corresponding placeholders in a format string. This technique creates more readable and maintainable code when you need to insert multiple dictionary values into a text template.

  • The format() method looks for placeholders that match dictionary keys
  • The **person syntax expands the dictionary into individual keyword arguments
  • Python raises a KeyError if a placeholder doesn't match any dictionary key

This approach particularly shines when working with form letters, report templates, or any situation where you need to combine dictionary data into a predefined text structure. The resulting code is cleaner than concatenation or multiple format arguments.

Advanced dictionary printing techniques

Building on the basic printing methods, Python offers powerful modules and formatting techniques that transform complex dictionary data into highly readable, well-structured output for both developers and end users.

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)
{'location': {'city': 'New York',
              'country': 'USA'},
 'person': {'age': 30, 'name': 'John'}}

The pprint module transforms complex nested dictionaries into a more readable format. It automatically handles indentation and line breaks, making deeply nested structures easier to understand at a glance.

  • The width parameter controls the maximum line length before wrapping occurs
  • Each nested level receives consistent indentation for visual hierarchy
  • Dictionary items appear alphabetically by default, helping you locate specific keys quickly

This formatting proves especially valuable when debugging or logging nested data structures where standard print() would produce a dense, hard-to-parse single line. The clear visual structure helps you spot patterns and relationships in your data more effectively.

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)
{
    "name": "John",
    "age": 30,
    "city": "New York"
}

The json.dumps() function converts Python dictionaries into JSON-formatted strings, creating output that's both human-readable and compatible with other systems. The indent parameter adds consistent spacing that visually organizes the data hierarchy.

  • Setting indent=4 creates four spaces of indentation for each nested level
  • The function automatically wraps each key-value pair on a new line
  • JSON formatting converts Python's single quotes to double quotes, following the JSON standard

This approach works particularly well when you need to share dictionary data with other developers or systems. The structured output makes it easy to spot relationships between data elements while maintaining a format that's ready for data exchange.

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")
Inventory:
apple      :  10 units
banana     :  15 units
orange     :   8 units
grape      :  25 units

String formatting methods create clean, aligned dictionary output that's perfect for displaying tabular data. The ljust() method pads strings with spaces on the right side, while :3d reserves three spaces for integer values.

  • The ljust(10) ensures each item name occupies exactly 10 characters, creating a uniform left column
  • The :3d format specifier aligns numbers in the right column, making quantities easy to scan
  • The colon separator adds visual structure between the columns

This formatting technique transforms raw dictionary data into a clear, professional-looking table. It's especially useful when presenting inventory lists, configuration settings, or any data that benefits from columnar alignment.

Get unstuck faster with Claude

Claude is an AI assistant from Anthropic that helps developers write better code, debug issues, and understand programming concepts. It combines deep technical knowledge with natural conversation to provide clear, accurate guidance.

Working alongside you like an experienced mentor, Claude helps you get unstuck when dealing with dictionary printing challenges, complex data structures, or any Python development task. It explains concepts step-by-step and suggests practical solutions tailored to your needs.

Start accelerating your Python development today. Sign up for free at Claude.ai and get personalized help with your coding questions.

Some real-world applications

Building on the dictionary printing techniques we've explored, these real-world examples demonstrate how Python dictionaries help developers create practical data displays for everyday applications.

Displaying user settings with status indicators

The status indicator pattern transforms boolean settings into visual checkmarks and crosses, creating an intuitive display that helps users quickly scan their current configuration state.

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 creates a user-friendly display of application settings stored in a dictionary. The dictionary user_settings maps setting names to boolean values that indicate whether each feature is enabled or disabled.

The for loop iterates through the dictionary using items() to access both keys and values. For each setting, the code performs two key transformations:

  • Converts True/False values into checkmark (✓) or cross (✗) symbols using a conditional expression
  • Formats setting names by replacing underscores with spaces and capitalizing words using replace() and title()

The f-string combines these elements into a clean, readable output that makes it easy to scan the current state of all settings at a glance.

Creating a mini dashboard from website analytics data

This example demonstrates how to transform raw website analytics data into a clean, scannable dashboard using Python's string formatting capabilities and dictionary operations.

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 code creates a polished analytics dashboard by combining Python's dictionary structure with advanced string formatting. The analytics dictionary stores key metrics as numerical values. Each print() statement uses f-strings with specialized formatting codes to display the data clearly:

  • The :, format code adds thousands separators to large numbers
  • The :.1% and :.2% codes convert decimals to percentages with specific decimal places
  • The // and % operators convert seconds into minutes and remaining seconds

The output transforms raw numbers into a readable format that makes sense for each metric type. This approach lets you present complex data in a way that's immediately meaningful to users.

Common errors and challenges

Python dictionaries can trigger several common errors that frustrate developers when printing or accessing data—understanding these challenges helps you write more reliable code.

Handling KeyError when accessing non-existent keys

A KeyError occurs when your code tries to access a dictionary key that doesn't exist. This common Python exception can crash your program if not handled properly. The following code demonstrates what happens when we attempt to access a missing phone key in a dictionary.

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

The code fails because it directly references the non-existent 'phone' key without first checking if it exists. This triggers Python's built-in error handling. The following code demonstrates a safer approach to accessing dictionary values.

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

The code demonstrates a defensive programming approach to handle missing dictionary keys. Instead of directly accessing values, it first checks for key existence using the in operator. This prevents the KeyError exception that would crash your program.

  • Always verify key existence before accessing dictionary values in production code
  • Use the get() method as an alternative to provide default values
  • Watch for this error when working with user input or external data sources where dictionary structure isn't guaranteed

This pattern proves especially valuable when processing data from APIs, user forms, or configuration files where missing keys are common. The conditional check creates more resilient code that gracefully handles incomplete data.

Using the get() method to handle missing keys

The get() method provides a safer alternative to direct key access when working with dictionaries. Instead of crashing with a KeyError, it returns a default value when a key doesn't exist. The following code demonstrates what happens when we try to access a missing key directly.

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

The code fails because it directly accesses the language key without first checking its existence. This triggers a KeyError exception that halts program execution. Let's examine a more robust approach using the get() method.

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

The get() method provides a safer way to access dictionary values by returning a default value when a key doesn't exist. In the example, preferences.get('language', 'default') returns 'default' if the language key is missing instead of raising an error.

  • Watch for this pattern when working with data from external sources like APIs or user input
  • Use get() whenever you're unsure if a key exists in your dictionary
  • The second parameter of get() lets you specify any fallback value. This creates more resilient code that won't break unexpectedly

Dealing with TypeError when printing dictionaries with mixed types

A TypeError occurs when you perform operations on incompatible data types in a dictionary. This common issue surfaces when mixing strings, integers, and None values without proper type conversion. The following code demonstrates how attempting arithmetic with mixed types leads to errors.

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

The code fails because it attempts to concatenate string values with None using the + operator. Python can't automatically combine these different data types. The following example shows the proper way to handle mixed data types in dictionaries.

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 code demonstrates proper type handling by converting string values to integers before performing arithmetic. It uses conditional expressions to check for None values and provides default values of 0 when needed. This pattern prevents TypeError exceptions that commonly occur when working with data from external sources like APIs or CSV files.

  • Watch for this error when processing user input or imported data where type consistency isn't guaranteed
  • Always validate and convert data types before performing operations
  • Consider using type hints and data validation libraries for larger applications

The solution creates a robust foundation for handling mixed data types in dictionaries. This approach proves especially valuable when building data processing pipelines or analytics systems where data quality varies.

Learning or leveling up? Use Claude

Claude combines advanced coding expertise with intuitive teaching abilities to guide you through Python development challenges. It excels at breaking down complex programming concepts into clear, actionable steps while adapting explanations to your skill level.

Here are some example prompts to help you master dictionary printing in Python:

  • Debug Help: Ask "Why does my dictionary print show 'TypeError' when combining strings and integers?" and Claude will explain type conversion solutions
  • Code Review: Ask "How can I make this dictionary output more readable?" and Claude will suggest formatting improvements using pprint or JSON
  • Feature Implementation: Ask "Show me how to create a settings dashboard with checkmarks" and Claude will provide a working example with visual indicators
  • Best Practices: Ask "What's the safest way to handle missing dictionary keys?" and Claude will demonstrate error handling techniques using get()

Experience personalized Python guidance by signing up for free at Claude.ai.

For a more integrated development experience, Claude Code brings AI assistance directly into your terminal, enabling seamless collaboration while you code.

FAQs

Additional Resources

How to find the factorial of a number in Python

2025-05-30
14 min
 read
Read more

How to sort a list alphabetically in Python

2025-05-30
14 min
 read
Read more

How to compare two dictionaries in Python

2025-05-30
14 min
 read
Read more

Leading companies build with Claude

ReplitCognitionGithub CopilotCursorSourcegraph
Try Claude
Get API Access
Copy
Expand