python
programming
dictionary
keys
tutorial

How to print a dictionary's key?

Master System Design with Codemia

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

Introduction

Python dictionaries store data as key-value pairs, and there are several ways to access and print just the keys. The most common approach is dict.keys(), which returns a view object of all keys. You can also iterate directly over the dictionary (which yields keys by default), use list comprehensions, or unpack keys with *. Since Python 3.7, dictionaries maintain insertion order, so keys are printed in the order they were added.

Using dict.keys()

python
1person = {"name": "Alice", "age": 30, "city": "New York"}
2
3# Print all keys
4print(person.keys())
5# dict_keys(['name', 'age', 'city'])
6
7# Convert to list
8keys_list = list(person.keys())
9print(keys_list)
10# ['name', 'age', 'city']
11
12# Print each key on its own line
13for key in person.keys():
14    print(key)
15# name
16# age
17# city

dict.keys() returns a dict_keys view — a dynamic view that updates if the dictionary changes.

Iterating Directly Over the Dictionary

python
1person = {"name": "Alice", "age": 30, "city": "New York"}
2
3# Iterating over a dict yields keys by default
4for key in person:
5    print(key)
6# name
7# age
8# city
9
10# This is equivalent to iterating over person.keys()

for key in dict is the most Pythonic way to iterate over keys. Calling .keys() is optional — both produce the same result.

Printing Keys with Values

python
1person = {"name": "Alice", "age": 30, "city": "New York"}
2
3# Print key-value pairs
4for key, value in person.items():
5    print(f"{key}: {value}")
6# name: Alice
7# age: 30
8# city: New York
9
10# Print only keys from items()
11for key, _ in person.items():
12    print(key)

Unpacking Keys with *

python
1person = {"name": "Alice", "age": 30, "city": "New York"}
2
3# Unpack into print
4print(*person)
5# name age city
6
7# Unpack with custom separator
8print(*person, sep=", ")
9# name, age, city
10
11# Unpack with newlines
12print(*person, sep="\n")
13# name
14# age
15# city

The * operator unpacks the dictionary's keys as separate arguments to print().

Accessing Specific Keys

python
1person = {"name": "Alice", "age": 30, "city": "New York"}
2
3# Check if a key exists
4if "name" in person:
5    print("'name' is a key")
6
7# Get the first key (Python 3.7+ maintains order)
8first_key = next(iter(person))
9print(first_key)  # name
10
11# Get the last key
12last_key = list(person)[-1]
13print(last_key)  # city
14
15# Get keys matching a condition
16numeric_keys = [k for k, v in person.items() if isinstance(v, int)]
17print(numeric_keys)  # ['age']

Nested Dictionary Keys

python
1config = {
2    "database": {
3        "host": "localhost",
4        "port": 5432
5    },
6    "cache": {
7        "driver": "redis",
8        "ttl": 300
9    }
10}
11
12# Top-level keys
13print(list(config.keys()))
14# ['database', 'cache']
15
16# Nested keys
17for section, settings in config.items():
18    print(f"{section}: {list(settings.keys())}")
19# database: ['host', 'port']
20# cache: ['driver', 'ttl']
21
22# All keys flattened (recursive)
23def all_keys(d, prefix=""):
24    keys = []
25    for k, v in d.items():
26        full_key = f"{prefix}.{k}" if prefix else k
27        keys.append(full_key)
28        if isinstance(v, dict):
29            keys.extend(all_keys(v, full_key))
30    return keys
31
32print(all_keys(config))
33# ['database', 'database.host', 'database.port', 'cache', 'cache.driver', 'cache.ttl']

Sorting Keys

python
1scores = {"Charlie": 85, "Alice": 92, "Bob": 78}
2
3# Alphabetically sorted keys
4for key in sorted(scores):
5    print(f"{key}: {scores[key]}")
6# Alice: 92
7# Bob: 78
8# Charlie: 85
9
10# Keys sorted by value
11for key in sorted(scores, key=scores.get, reverse=True):
12    print(f"{key}: {scores[key]}")
13# Alice: 92
14# Charlie: 85
15# Bob: 78

Common Pitfalls

  • Modifying a dictionary while iterating over its keys: Adding or removing keys during for key in dict raises RuntimeError: dictionary changed size during iteration. Copy the keys first with list(dict.keys()) if you need to modify the dict during iteration.
  • Assuming dict.keys() returns a list: dict.keys() returns a view object, not a list. It does not support indexing (keys[0]). Convert with list(dict.keys()) if you need list operations.
  • Using dict.keys() for membership testing: if key in dict.keys() works but is unnecessary. if key in dict is faster and more Pythonic — it checks membership directly without creating a view.
  • Expecting ordered keys in Python 3.6 and earlier: Dictionaries are guaranteed insertion-ordered only from Python 3.7+. In Python 3.6, CPython's dict is ordered as an implementation detail, but it is not guaranteed by the language specification. Use collections.OrderedDict for guaranteed order on older versions.
  • Printing dict_keys object instead of formatted output: print(dict.keys()) outputs dict_keys(['a', 'b']) which may not be the desired format. Convert to list or use * unpacking for cleaner output.

Summary

  • Use for key in dict to iterate over keys — the most Pythonic approach
  • Use dict.keys() explicitly when you need the view object for set operations (union, intersection)
  • Use print(*dict, sep=", ") to print keys in a single line with a custom separator
  • Use sorted(dict) to iterate over keys in alphabetical order
  • Convert with list(dict.keys()) when you need indexing or need to modify the dict during iteration
  • Dictionaries maintain insertion order in Python 3.7+ — keys print in the order they were added

Course illustration
Course illustration

All Rights Reserved.