keys() returns a view of the dict's keys, printed as dict_keys([...]). A view is not a copy: it is a window onto the dict, so it always shows the current keys in insertion order.
Because keys are unique and hashable, the view is set-like: it supports -, &, |, and ^ with sets and other key views. That makes it ideal for comparing which fields two records share.
dict.keys() is an instance method of the built-in dict type: call it on a dictionary with dot notation, such as menu.keys(...). No import is needed.
Syntax
Call it with no arguments. Most code loops over the view or converts it with list().
python
view = d.keys()
for key in d.keys():
print(key)
Call
What it does
{"a": 1, "b": 2}.keys()
Returns dict_keys(['a', 'b']).
list({"x": 0, "y": 0}.keys())
Returns ['x', 'y'].
{"a": 1, "b": 2}.keys() - {"a"}
Returns {'b'}, a regular set.
key in d and key in d.keys() give the same answer with the same fast lookup; the shorter form is usual. list(d) equals list(d.keys()).
Method signatures
python
dict.keys()
# returns: a dict_keys view of the dict's keys
Parameters
keys() takes no parameters.
Return Value
Return Value
Description
dict_keys
A live, read-only view of the keys in insertion order. It supports len(), in, iteration, reversed() (Python 3.8+), and set operators.
Python Examples
Example 1 — Inspect the Keys of a Cafe Menu
Print a keys view, test membership, convert it to a list, and see what happens when you try to index it.
python
menu = {"latte": 4.5, "mocha": 5.0, "tea": 3.0}
names = menu.keys()
print(names)
print("mocha" in names, "chai" in menu)
print(list(names), len(names))
try:
print(names[0])
except TypeError:
print("views cannot be indexed; use list(names)[0]")
Output
dict_keys(['latte', 'mocha', 'tea'])
True False
['latte', 'mocha', 'tea'] 3
views cannot be indexed; use list(names)[0]
How It Works
Readable repr. Printing the view shows dict_keys(...) wrapped around the keys in menu order.
Two ways to test."mocha" in names and "chai" in menu both check keys, never prices.
Convert when needed.list(names) makes a real list, while len() works on the view directly.
No positions. Indexing the view raises TypeError; a view supports lookups by key, not by position.
Example 2 — Watch a Keys View Follow a Server Registry
Create the view once, then add and remove servers and print the same view again.