python
dictionary
key-value pairs
print
programming

How do I print the key-value pairs of a dictionary in python

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

The standard way to print key-value pairs from a Python dictionary is to iterate with .items(), which returns each key-value pair as a tuple. You can loop through them with a for loop, format them with f-strings, or use pprint for nested dictionaries. For quick debugging, print(dict) shows the entire dictionary at once.

Basic: print(dict)

python
1user = {"name": "Alice", "age": 30, "city": "NYC"}
2
3print(user)
4# {'name': 'Alice', 'age': 30, 'city': 'NYC'}

This prints the dictionary in its default representation. Fine for quick debugging, but not formatted for readability.

Iterating with .items()

python
1user = {"name": "Alice", "age": 30, "city": "NYC"}
2
3for key, value in user.items():
4    print(f"{key}: {value}")
5# name: Alice
6# age: 30
7# city: NYC

.items() returns a view of (key, value) tuples. Unpacking into key, value in the loop gives clean access to both.

Formatting Options

python
1config = {"host": "localhost", "port": 5432, "debug": True}
2
3# f-string
4for k, v in config.items():
5    print(f"{k} = {v}")
6
7# format()
8for k, v in config.items():
9    print("{}: {}".format(k, v))
10
11# Aligned output with padding
12for k, v in config.items():
13    print(f"{k:<10} {v}")
14# host       localhost
15# port       5432
16# debug      True
17
18# As key=value pairs
19for k, v in config.items():
20    print(f"{k}={v!r}")
21# host='localhost'
22# port=5432
23# debug=True

!r uses repr() which adds quotes around strings, making the output copy-pasteable.

Using pprint (Pretty Print)

python
1from pprint import pprint
2
3data = {
4    "users": [
5        {"name": "Alice", "scores": [85, 92, 78]},
6        {"name": "Bob", "scores": [90, 88, 95]},
7    ],
8    "metadata": {"version": 2, "generated": "2025-01-01"},
9}
10
11pprint(data)
12# {'metadata': {'generated': '2025-01-01', 'version': 2},
13#  'users': [{'name': 'Alice', 'scores': [85, 92, 78]},
14#            {'name': 'Bob', 'scores': [90, 88, 95]}]}
15
16# Control width and depth
17pprint(data, width=40, depth=2)

pprint automatically indents nested structures. It sorts keys alphabetically by default.

Using json.dumps for Pretty Output

python
1import json
2
3data = {"name": "Alice", "scores": [85, 92, 78], "active": True}
4
5print(json.dumps(data, indent=2))
6# {
7#   "name": "Alice",
8#   "scores": [
9#     85,
10#     92,
11#     78
12#   ],
13#   "active": true
14# }

json.dumps with indent produces clean, readable output. Note: it converts Python True to JSON true and does not handle non-serializable types.

Printing Only Keys or Values

python
1user = {"name": "Alice", "age": 30, "city": "NYC"}
2
3# Just keys
4for key in user:
5    print(key)
6# name
7# age
8# city
9
10# Just values
11for value in user.values():
12    print(value)
13# Alice
14# 30
15# NYC
16
17# Keys as a list
18print(list(user.keys()))
19# ['name', 'age', 'city']

One-Line Approaches

python
1user = {"name": "Alice", "age": 30, "city": "NYC"}
2
3# Join with newlines
4print('\n'.join(f"{k}: {v}" for k, v in user.items()))
5
6# Using str.join with commas
7print(', '.join(f"{k}={v}" for k, v in user.items()))
8# name=Alice, age=30, city=NYC
9
10# Unpack with print
11print(*user.items(), sep='\n')
12# ('name', 'Alice')
13# ('age', 30)
14# ('city', 'NYC')

Printing Nested Dictionaries

python
1def print_dict(d, indent=0):
2    """Recursively print nested dictionaries."""
3    for key, value in d.items():
4        prefix = "  " * indent
5        if isinstance(value, dict):
6            print(f"{prefix}{key}:")
7            print_dict(value, indent + 1)
8        elif isinstance(value, list):
9            print(f"{prefix}{key}:")
10            for item in value:
11                if isinstance(item, dict):
12                    print_dict(item, indent + 1)
13                else:
14                    print(f"{prefix}  - {item}")
15        else:
16            print(f"{prefix}{key}: {value}")
17
18config = {
19    "database": {
20        "host": "localhost",
21        "port": 5432,
22        "credentials": {
23            "user": "admin",
24            "password": "secret"
25        }
26    },
27    "features": ["auth", "logging"]
28}
29
30print_dict(config)
31# database:
32#   host: localhost
33#   port: 5432
34#   credentials:
35#     user: admin
36#     password: secret
37# features:
38#   - auth
39#   - logging

Tabular Output with tabulate

python
1from tabulate import tabulate
2
3user = {"name": "Alice", "age": 30, "city": "NYC", "role": "Engineer"}
4
5print(tabulate(user.items(), headers=["Key", "Value"], tablefmt="grid"))
6# +------+----------+
7# | Key  | Value    |
8# +------+----------+
9# | name | Alice    |
10# | age  | 30       |
11# | city | NYC      |
12# | role | Engineer |
13# +------+----------+

Install with pip install tabulate.

Common Pitfalls

  • Modifying dict during iteration: Adding or removing keys while iterating with .items() raises RuntimeError. Create a copy first: for k, v in list(d.items()):.
  • Printing large dicts: print(big_dict) outputs everything on one line. Use pprint or json.dumps(indent=2) for readability.
  • Non-string keys with json.dumps: json.dumps({1: "a"}) raises TypeError. JSON only supports string keys. Use pprint instead, or convert keys: json.dumps({str(k): v for k, v in d.items()}).
  • Order assumptions: Python 3.7+ dicts maintain insertion order. Printing shows keys in insertion order. pprint sorts keys alphabetically. Use sort_dicts=False (Python 3.8+) to preserve order.
  • repr vs str: print(value) uses str() which may hide type information. Use print(repr(value)) or f"{value!r}" to see exact types and escape characters.

Summary

  • Use for key, value in dict.items() with f-strings for basic printing
  • Use pprint.pprint() for readable nested dictionary output
  • Use json.dumps(dict, indent=2) for JSON-formatted output
  • Use f"{key:<10} {value}" for aligned columnar output
  • Use .keys(), .values(), or .items() to access specific parts of the dictionary
  • For production logging, convert to JSON or use structured logging libraries

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.