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()
dict.keys() returns a dict_keys view — a dynamic view that updates if the dictionary changes.
Iterating Directly Over the Dictionary
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
Unpacking Keys with *
The * operator unpacks the dictionary's keys as separate arguments to print().
Accessing Specific Keys
Nested Dictionary Keys
Sorting Keys
Common Pitfalls
- Modifying a dictionary while iterating over its keys: Adding or removing keys during
for key in dictraisesRuntimeError: dictionary changed size during iteration. Copy the keys first withlist(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 withlist(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 dictis 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.OrderedDictfor guaranteed order on older versions. - Printing
dict_keysobject instead of formatted output:print(dict.keys())outputsdict_keys(['a', 'b'])which may not be the desired format. Convert to list or use*unpacking for cleaner output.
Summary
- Use
for key in dictto 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

