python
dictionary
printing
for loop
programming tips

How to print a dictionary line by line in Python?

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Printing a dictionary line by line in Python is usually just a matter of iterating over its items and formatting the output clearly. The right technique depends on whether the dictionary is flat or nested, whether order matters, and whether the output is for humans or for another tool.

The Basic Pattern

For a simple dictionary, iterate over items() and print one key-value pair per line.

python
1data = {
2    "name": "Ada",
3    "language": "Python",
4    "level": "senior"
5}
6
7for key, value in data.items():
8    print(f"{key}: {value}")

Output:

text
name: Ada
language: Python
level: senior

This is the normal answer for most scripts.

Why items() Is Better Than Iterating Keys Alone

You could loop through the keys and index back into the dictionary, but items() is cleaner and avoids an extra lookup.

Less direct:

python
for key in data:
    print(f"{key}: {data[key]}")

Better:

python
for key, value in data.items():
    print(f"{key}: {value}")

The second form makes the intent explicit and scales better when you want to transform both parts of the pair.

Printing in a Stable Order

Modern Python preserves insertion order, but sometimes you want alphabetical output instead. In that case, sort the keys or items explicitly.

python
1data = {
2    "zeta": 3,
3    "alpha": 1,
4    "beta": 2
5}
6
7for key in sorted(data):
8    print(f"{key}: {data[key]}")

If predictable ordering matters in logs, tests, or documentation, make the ordering explicit rather than depending on how the dictionary happened to be created.

Formatting for Readability

Simple print is often enough, but aligned output is easier to scan when keys vary in length.

python
1data = {
2    "username": "ada",
3    "email": "[email protected]",
4    "active": True
5}
6
7width = max(len(key) for key in data)
8
9for key, value in data.items():
10    print(f"{key:<{width}} : {value}")

That produces a cleaner column-like layout. It is a small improvement, but it matters when dictionaries are printed in debugging tools or CLI output.

Nested Dictionaries Need a Different Strategy

If values can themselves be dictionaries, a flat one-line print may no longer be readable. In that case, use recursion or a formatting tool.

Example recursive printer:

python
1def print_dict(d, indent=0):
2    prefix = " " * indent
3    for key, value in d.items():
4        if isinstance(value, dict):
5            print(f"{prefix}{key}:")
6            print_dict(value, indent + 2)
7        else:
8            print(f"{prefix}{key}: {value}")
9
10
11config = {
12    "database": {
13        "host": "localhost",
14        "port": 5432
15    },
16    "debug": True
17}
18
19print_dict(config)

This is far more readable than dumping nested dictionaries as raw Python literals line by line.

Use pprint or JSON for Structured Output

If the goal is debugging rather than custom formatting, the standard library already provides good tools.

With pprint:

python
1from pprint import pprint
2
3data = {
4    "name": "Ada",
5    "skills": ["Python", "SQL", "Docker"],
6    "settings": {"theme": "light", "alerts": True}
7}
8
9pprint(data)

With JSON-style pretty printing:

python
import json

print(json.dumps(data, indent=2, sort_keys=True))

Use these when you want structure preserved without writing your own formatting logic.

Converting Values for Display

Be careful when dictionary values are objects, lists, or dates. The default string representation may be correct for debugging but poor for user-facing output.

For example:

python
1from datetime import date
2
3data = {
4    "user": "ada",
5    "created": date(2026, 3, 7)
6}
7
8for key, value in data.items():
9    if hasattr(value, "isoformat"):
10        value = value.isoformat()
11    print(f"{key}: {value}")

Small display rules like this can make logs and CLI output much more usable.

Common Pitfalls

The most common mistake is printing the whole dictionary object and calling that "line by line." print(data) gives one string representation, not a formatted per-entry output.

Another mistake is using for key in data when items() would make the code clearer. Both work, but items() is the right default when you need keys and values.

Developers also forget about ordering. If output order matters for testing or comparison, sort explicitly.

Finally, nested dictionaries often need special formatting. A simple one-line loop is fine for flat data, but it becomes noisy and hard to read once the values contain more structure.

Summary

  • For flat dictionaries, iterate over data.items() and print one pair per line.
  • Use explicit sorting when output order matters.
  • Format columns if the output is meant for people to scan quickly.
  • For nested dictionaries, use recursion, pprint, or JSON pretty printing.
  • Treat display formatting as a separate concern when values are complex objects.

Course illustration
Course illustration

All Rights Reserved.