How to print the key of a dictionary in Python
Learn how to print dictionary keys in Python. This guide covers various methods, tips, real-world uses, and common error debugging.

Python dictionaries store data as key-value pairs. It's a common task to isolate and print just the keys for data iteration or to debug your code effectively.
In this article, you'll explore several methods to print dictionary keys, such as the keys() method and simple loops. We also provide tips, real-world examples, and advice to help you debug common problems.
Using a simple for loop to print dictionary keys
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
for key in my_dict:
print(key)--OUTPUT--apple
banana
cherry
Iterating directly over a dictionary with a for loop is the most straightforward way to access its keys. This works because dictionaries in Python are iterable, and by default, this iteration process yields the keys one by one. It's a clean and Pythonic approach that avoids calling any extra methods, making your code more readable.
In the example, the loop assigns each key from my_dict to the variable key in sequence. The print() function then displays each key on a new line, giving you a simple output of all the keys in your dictionary.
Common methods for accessing keys
Building on simple loops, you can gain more control by using specific methods like keys() to collect, view, or even filter keys based on criteria.
Using the keys() method to get all keys
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
keys = my_dict.keys()
print(keys)
print(list(keys)) # Converting to a list--OUTPUT--dict_keys(['apple', 'banana', 'cherry'])
['apple', 'banana', 'cherry']
The keys() method gives you a dynamic view object containing all the keys in your dictionary. This isn't a static list; it's a live representation that updates if the dictionary changes. When you print this view object, you'll see it prefixed with dict_keys().
- To use the keys like a regular list, you can convert the view object using the
list()constructor. - This creates a new list that you can then index, slice, or sort as needed.
Using list comprehension with dictionary keys
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
keys_list = [key for key in my_dict]
print(keys_list)--OUTPUT--['apple', 'banana', 'cherry']
List comprehension offers a concise, one-line syntax for creating lists. The expression [key for key in my_dict] builds a new list by iterating through the dictionary, just like a standard for loop, but in a more compact form.
- This approach is often considered more "Pythonic" because it's both expressive and efficient.
- It directly creates a
list, so you don't need to convert a view object as you would with thekeys()method.
Filtering keys based on conditions
my_dict = {"apple": 1, "banana": 2, "cherry": 3, "apricot": 4}
a_keys = [key for key in my_dict if key.startswith('a')]
print(a_keys)--OUTPUT--['apple', 'apricot']
You can easily filter keys by adding an if condition to your list comprehension. This lets you create a new list containing only the keys that meet specific criteria. It's a powerful way to selectively extract information from your dictionary in a single, readable line.
- The condition
if key.startswith('a')is evaluated for every key in the dictionary. - Only keys that satisfy this condition—in this case, those starting with 'a'—are added to the new list,
a_keys.
Advanced key operations
Building on the fundamentals, you can perform more advanced key manipulations like set operations, navigating nested dictionaries, and applying functional programming patterns.
Using set operations with dictionary keys
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 3, "c": 4}
common_keys = dict1.keys() & dict2.keys()
all_keys = dict1.keys() | dict2.keys()
print(f"Common keys: {common_keys}")
print(f"All keys: {all_keys}")--OUTPUT--Common keys: {'b'}
All keys: {'a', 'b', 'c'}
The keys() method returns a view object that supports set-like operations. This lets you compare keys from different dictionaries efficiently without first converting them to lists.
- The intersection operator (
&) finds keys that exist in both dictionaries, such as'b'in the example. - The union operator (
|) gathers all unique keys from both dictionaries into a single set.
This approach is a concise way to handle key comparisons and manipulations directly.
Accessing keys in nested dictionaries
nested_dict = {"person": {"name": "John", "age": 30}, "job": {"title": "Developer"}}
for outer_key, inner_dict in nested_dict.items():
print(f"Keys in {outer_key}: {list(inner_dict.keys())}")--OUTPUT--Keys in person: ['name', 'age']
Keys in job: ['title']
To navigate a nested dictionary, where values are themselves dictionaries, you can iterate through it layer by layer. The items() method is perfect for this, letting you access both the key and the value of the outer dictionary in each loop iteration.
- The loop unpacks each top-level item into an
outer_keyand its correspondinginner_dict. - Once you have the
inner_dict, you can callkeys()on it to retrieve the keys from that specific nested level.
Using functional programming with dictionary keys
from functools import reduce
dicts = [{"a": 1, "b": 2}, {"b": 3, "c": 4}, {"a": 5, "d": 6}]
all_keys = reduce(lambda keys, d: keys | set(d.keys()), dicts, set())
print(f"All keys from multiple dictionaries: {all_keys}")--OUTPUT--All keys from multiple dictionaries: {'a', 'b', 'c', 'd'}
For a more functional approach, you can use reduce() from the functools module to aggregate keys from a list of dictionaries. This function repeatedly applies an operation to a sequence, boiling it down to a single result.
- The lambda function
lambda keys, d: keys | set(d.keys())defines this operation. It takes an accumulator (keys) and the next dictionary (d). - In each step, it performs a set union using the
|operator, merging the accumulated keys with the keys from the current dictionary. - The process starts with an empty
set(), ensuring the final result is a collection of all unique keys.
Move faster with Replit
Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.
For the key manipulation techniques we've explored, Replit Agent can turn them into production-ready tools:
- Build a configuration validator that checks a settings dictionary for required keys and flags any extras.
- Create a tool that compares feature flag configurations between two environments by finding common or unique keys using set operations like
&and|. - Deploy a simple JSON data explorer that lets you navigate nested objects and lists all keys at each level.
Bring your idea to life by describing it. Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser.
Common errors and challenges
Even simple tasks like printing keys can lead to common errors, but they're easy to avoid once you know what to look for.
Handling KeyError when accessing non-existent keys
A KeyError is one of the most common issues you'll face. It occurs when you try to access a dictionary key that doesn't exist. Your program will stop and raise this error because it can't find what you're asking for.
- To prevent this, you can check if a key exists before trying to use it. The
inkeyword is perfect for this:if 'my_key' in my_dict:. - Another great option is the
get()method. Instead of raising an error,my_dict.get('my_key')will simply returnNoneif the key isn't found. You can also provide a default value, likemy_dict.get('my_key', 0), to return if the key is missing.
Avoiding errors when modifying a dictionary during iteration
Python throws a RuntimeError if you try to add or remove keys from a dictionary while you're iterating over it. The dictionary's size can't change during the loop, as this would disrupt the iteration process. The solution is to loop over a copy of the keys, which leaves the original dictionary free to be modified. You can create this copy easily by converting the keys to a list: for key in list(my_dict):.
Distinguishing between keys() and items() when iterating
It's easy to confuse what keys() and items() return. The keys() method gives you only the keys, while items() provides key-value pairs. A common mistake is trying to unpack a key and value from keys(), like for key, value in my_dict.keys():. This will cause a ValueError because you're trying to assign a single item (the key) to two variables. If you need both the key and the value, always use items(). If you only need the keys, iterating directly over the dictionary (for key in my_dict:) is the cleanest approach.
Handling KeyError when accessing non-existent keys
A KeyError is a frequent stumbling block that halts your program when you try to retrieve a key that isn't in the dictionary. It's a direct signal that your code expected data that wasn't there. See this error in action below.
user_data = {"name": "John", "age": 30}
email = user_data["email"] # This will raise KeyError
print(f"User email: {email}")
The code attempts to access the "email" key, but the user_data dictionary only contains keys for "name" and "age". This mismatch triggers the KeyError. The example below shows how to safely access dictionary keys without causing a crash.
user_data = {"name": "John", "age": 30}
email = user_data.get("email", "Not provided")
print(f"User email: {email}")
To avoid a crash, the code uses the get() method. It safely attempts to retrieve the "email" key. Since the key doesn't exist, get() returns the default value you provide—in this case, "Not provided"—instead of raising an error. This approach is perfect when you're handling data where certain keys might be optional, such as user profiles or API responses, ensuring your program runs smoothly.
Avoiding errors when modifying a dictionary during iteration
It's a classic Python pitfall to modify a dictionary while iterating over it. If you add or remove keys during a loop, Python raises a RuntimeError. This happens because changing the dictionary's size disrupts the iteration process, making it unstable.
The following code demonstrates what happens when you attempt to delete a key from a dictionary you're currently looping through.
colors = {"red": 1, "green": 2, "blue": 3}
for key in colors:
if key == "green":
del colors[key] # RuntimeError: dictionary changed during iteration
The for loop iterates over the colors dictionary, but the del colors[key] operation tries to modify that same dictionary mid-loop. Python prohibits this, triggering a RuntimeError. The following example shows how to perform this action safely.
colors = {"red": 1, "green": 2, "blue": 3}
keys_to_remove = [key for key in colors if key == "green"]
for key in keys_to_remove:
del colors[key]
print(colors)
The safe approach is to iterate over a copy, not the original dictionary. The code first builds a separate list, keys_to_remove, holding only the keys you want to delete. A second loop then iterates over this new list to safely remove each key from the original colors dictionary. This two-step process prevents a RuntimeError because the dictionary’s size isn’t changing during the loop that’s modifying it. This is crucial when filtering or cleaning data dynamically.
Distinguishing between keys() and items() when iterating
A frequent error is trying to access a value when your loop only provides the key. Iterating directly over a dictionary or its keys() gives you just the keys—not the values. This can lead to incorrect output, as shown in the code below.
products = {"apple": 0.99, "banana": 0.59, "orange": 1.29}
for key in products:
print(f"Product: {key}, Price: {key}") # Incorrectly uses key for price
The loop correctly assigns the product name to key. The problem is that the print function then uses this same key variable for the price, producing incorrect output. See the correct way to do this below.
products = {"apple": 0.99, "banana": 0.59, "orange": 1.29}
for key, value in products.items():
print(f"Product: {key}, Price: {value}")
To fix this, use the items() method, which provides both the key and value together. Your for loop can then unpack this key-value pair into two separate variables, like key and value. This is the correct pattern anytime you need to work with both pieces of data simultaneously within a loop. It’s essential for tasks like formatting output or performing calculations that involve the dictionary’s values, not just its keys.
Real-world applications
With the methods and error-handling covered, you can apply these skills to practical tasks like analyzing text or building command-line menus.
Analyzing text data with word frequency counts
A classic real-world application for dictionaries is counting word frequencies, where each word acts as a key to store its tally.
text = "the quick brown fox jumps over the lazy dog"
word_counts = {}
for word in text.split():
if word in word_counts:
word_counts[word] += 1
else:
word_counts[word] = 1
print(word_counts)
The code first uses text.split() to break the string into a list of words. It then loops through this list, processing one word at a time to populate the word_counts dictionary.
Inside the loop, an if statement checks if a word already exists as a key.
- If the key is present, its associated value is incremented by one using
+= 1. - If it's a new word, it's added to the dictionary with a starting value of
1.
This process builds the dictionary dynamically based on the contents of the input text.
Building a simple command-line menu system with dict keys
You can build a simple command-line menu by using a dictionary to map string commands as keys to their corresponding functions as values.
def say_hello(): print("Hello!")
def say_goodbye(): print("Goodbye!")
menu = {
"hello": say_hello,
"goodbye": say_goodbye,
"exit": lambda: print("Exiting program...")
}
command = "hello"
if command in menu:
menu[command]()
This example showcases a powerful Python feature: storing functions as dictionary values. The menu dictionary doesn't hold simple data; its values are callable functions like say_hello and even a compact lambda.
- The code first checks if the
commandstring is a valid key using theinoperator. - If the key exists,
menu[command]retrieves the function object, and the parentheses()immediately call it.
This technique allows you to select and execute behavior dynamically based on a string input, making your code flexible.
Get started with Replit
Put your new skills to work by building a real tool. Describe what you want to Replit Agent, like "a tool that compares two JSON files and lists common keys" or "a utility to explore a nested dictionary and print its keys."
Replit Agent writes the code, tests for errors, and deploys your app automatically. It handles the heavy lifting so you can focus on your idea. Start building with Replit.
Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.
Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.


.png)
.png)