dict.keys()

Returns a view of the dictionary's keys that always reflects its current contents.

Returns
A dict_keys view object.
Changes the original
No
On this page

Example

#
Python
modules = {"html": 11, "css": 9, "python": 12}

keys = modules.keys()
print(keys)
print(list(keys))

modules["react"] = 16
print(len(keys), "react" in keys)
Resultsaved result, you can check it
dict_keys(['html', 'css', 'python'])
['html', 'css', 'python']
4 True

Definition and usage

#

The keys() method returns a view object with the dictionary keys in insertion order. The view is not a copy: when the dictionary changes, the view immediately shows the new keys.

You can iterate over the view, check its length with len(), and test membership with in. Writing for key in dict or key in dict does the same thing without calling keys(), so the method is usually skipped in those spots.

A keys view behaves like a set and supports the &, |, and - operators. That lets you quickly find the keys shared by two dictionaries, or the ones missing from one of them. When you need a list, for example to read a key by index, convert the view with list().

Syntax

#
Syntax
dict.keys()

More examples

#
Comparing the keys of two dictionaries
Python
defaults = {"theme": "dark", "lang": "en", "sound": True}
user = {"lang": "fr", "avatar": "fox.png"}

print(sorted(defaults.keys() & user.keys()))
print(sorted(defaults.keys() - user.keys()))
print(sorted(user.keys() - defaults.keys()))
Resultsaved result, you can check it
['lang']
['sound', 'theme']
['avatar']
Removing keys in a loop
Python
scores = {"Emma": 92, "Jack": 0, "Mia": 0}

try:
    for name in scores.keys():
        if scores[name] == 0:
            del scores[name]
except RuntimeError as error:
    print("Error:", error)

for name in list(scores.keys()):
    if scores[name] == 0:
        del scores[name]

print(scores)
Resultsaved result, you can check it
Error: dictionary changed size during iteration
{'Emma': 92}

Good practices

#
  • To check for a key, write if key in dict: without .keys(). The effect is the same, and it reads shorter.
  • Don't add or remove keys while looping over a dictionary. Loop over a copy with list(dict), or build a new dictionary with a dict comprehension.

Related entries

#

Spotted a mistake or missing an example? Write to us.