Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Dictionaries and Sets

Python dict.keys() method

Reference for Python dict.keys(): get a live view of a dictionary's keys, loop over it, use set operations such as intersection, and avoid size-change errors.

The dict.keys() method returns a view of the keys of a dictionary. The view is not a list and holds no copy of the data; it reads the dictionary each time you use it, so later changes to the dictionary show up in a view you created earlier.

Most of the time you do not need keys() at all: iterating over a dictionary (for k in d) and testing membership (k in d) already work on keys. It earns its place when you want set-style operations or a method that returns a keys object.

Python
d = {"a": 1, "b": 2}
print(list(d.keys()))   # ['a', 'b']

Try it

Python Using the keys view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Live view and set operations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
dict.keys()

keys() takes no arguments.

Return value: a dict_keys view object. It supports len(), iteration, in, reversed() (Python 3.8+) and the set operators.

Raises: nothing when called; iterating while the dictionary changes size raises RuntimeError.

Usage notes

  • Insertion order. Keys come out in the order they were first added (guaranteed since Python 3.7). Updating the value of an existing key does not move it.
  • Live, not a snapshot. Use list(d.keys()) when you need the keys as they are right now, for example before deleting while looping.
  • Set-like. Keys are unique and hashable, so a keys view works with &, |, -, ^ and comparisons, and accepts any iterable on the other side of a method such as isdisjoint(). The result of an operator is a real set.
  • Not indexable. d.keys()[0] raises TypeError. Use next(iter(d)) for the first key or list(d) to index.
  • Looping. for k in d and for k in d.keys() are equivalent. The shorter form is the usual choice.
  • No size changes while iterating. Adding or deleting keys inside the loop raises RuntimeError. Changing values is fine.
  • Membership is fast. k in d and k in d.keys() are both constant-time hash look-ups. Do not write k in list(d.keys()).
  • Sorted output. sorted(d) returns a new list of keys in order. It does not change the dictionary.