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.
d = {"a": 1, "b": 2} print(list(d.keys())) # ['a', 'b']
Try it
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.
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
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 asisdisjoint(). The result of an operator is a realset. - Not indexable.
d.keys()[0]raisesTypeError. Usenext(iter(d))for the first key orlist(d)to index. - Looping.
for k in dandfor 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 dandk in d.keys()are both constant-time hash look-ups. Do not writek in list(d.keys()). - Sorted output.
sorted(d)returns a new list of keys in order. It does not change the dictionary.
Related
dict.values(),dict.items(),dict.get(),dict,set- Lessons: Dictionaries, Dictionary methods, Sets