Python Dictionary keys() Method

Short answer
dict.keys() returns a live, read-only view of all the keys in a dictionary, in insertion order. Convert it with list() when you need a regular list.

Most of the time you do not need to call keys() at all, because looping over a dictionary already gives you its keys. The method earns its place when you want an explicit, readable view of the key set: to compare two dictionaries, to count keys, or to turn the keys into a list. It belongs to the family of dictionary methods together with items() and values().

Like the others, keys() returns a view, not a list. The view stays in sync with the dictionary and uses almost no extra memory.

Quick facts
Syntaxmy_dict.keys()
ParametersNone
ReturnsA dict_keys view of the keys
OrderInsertion order (guaranteed since Python 3.7)
Time complexityO(1) to create; in is O(1) on average

What the dict_keys view is and how it behaves

keys() gives you a dict_keys object. You can loop over it, call len() on it and test membership with in. You cannot index it (d.keys()[0] fails) or sort it in place, because it is not a list. If the dictionary changes, the view changes with it.

Python
student = {"name": "Asha", "age": 21}
keys = student.keys()
print(keys)
student["city"] = "Pune"
print(keys)
print(len(keys))

The second print includes "city" even though we never called keys() again.

Set-like operations on keys

A keys view behaves like a set of the keys, so you can use & (common keys), | (all keys), - (keys only in the left one) and ^ (keys in exactly one) directly on two views, or on a view and any other set or list. This is a neat way to compare configurations or find missing fields.

Python
defaults = {"theme": 1, "font": 2, "lang": 3}
user = {"theme": 9, "font": 8}
print(sorted(defaults.keys() - user.keys()))
print(sorted(defaults.keys() & user.keys()))

We wrap the results in sorted() because a set has no guaranteed print order.

keys() vs looping over the dictionary directly

for k in d and for k in d.keys() do the same thing; the first is shorter and is the usual style. Likewise k in d is preferred over k in d.keys(): both are fast, but the shorter form is idiomatic. Use keys() when the view itself matters, for set operations, for passing the keys to a function, or when you want the code to say clearly that only keys are used. To get values or pairs instead, see values() and items().

Examples you can run

Press Run, then edit the code and run it again.

List the keys of a dictionary

list() turns the view into an ordinary list you can index and slice.

List the keys of a dictionary
menu = {"tea": 10, "coffee": 20, "juice": 30}
names = list(menu.keys())
print(names)
print(names[0])
Expected output['tea', 'coffee', 'juice']
tea

Find required fields that are missing

Subtracting key views shows which required keys the form lacks.

Find required fields that are missing
required = {"name", "email", "age"}
form = {"name": "Ravi", "age": 30}
missing = required - form.keys()
print(sorted(missing))
Expected output['email']

Check whether a key exists

Membership tests on a dictionary look at keys, never at values.

Check whether a key exists
stock = {"apples": 4, "pears": 0}
print("pears" in stock)
print(0 in stock)
print(0 in stock.values())
Expected outputTrue
False
True

Common mistakes

Indexing the keys view

✗ Wrong

d = {"a": 1, "b": 2}
first = d.keys()[0]
TypeError: 'dict_keys' object is not subscriptable

✓ Right

d = {"a": 1, "b": 2}
first = list(d.keys())[0]
print(first)

Convert to a list first, or use next(iter(d)) to get the first key.

Deleting keys while looping over keys()

✗ Wrong

d = {"a": 1, "b": 2}
for k in d.keys():
    del d[k]
RuntimeError: dictionary changed size during iteration

✓ Right

d = {"a": 1, "b": 2}
for k in list(d.keys()):
    del d[k]
print(d)

Loop over list(d.keys()) so you iterate over a snapshot while modifying the dictionary.

Python Dictionary keys() Method: questions people ask

What does dict.keys() return in Python 3?

It returns a dict_keys view object, not a list. The view reflects later changes to the dictionary.

How do I get the keys of a dictionary as a list?

Use list(my_dict) or list(my_dict.keys()). Both return the keys in insertion order.

Is dict.keys() sorted?

No. Keys come out in insertion order, not sorted order. Use sorted(my_dict) to get a sorted list of the keys.

Keep learning

Step-by-step lessons:
Python DictionariesPython Dictionary MethodsPython Sets

Related:
Python Dictionary values() MethodPython Dictionary items() MethodHow to Loop Through a Dictionary in PythonPython Dictionary get() Method

More in dictionary methods:
Python Dictionary get() MethodPython Dictionary items() MethodPython Dictionary values() MethodPython Dictionary update() MethodPython Dictionary pop() MethodPython Dictionary popitem() MethodPython Dictionary setdefault() MethodPython Dictionary clear() Method See all →