dict. keys()
Returns a view of the dictionary's keys that always reflects its current contents.
- Returns
- A
dict_keysview object. - Changes the original
- No
Example
#modules = {"html": 11, "css": 9, "python": 12}
keys = modules.keys()
print(keys)
print(list(keys))
modules["react"] = 16
print(len(keys), "react" in keys)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
#dict.keys()More examples
#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()))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)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
#- dict.values()Returns a view of the dictionary values, ready for loops, sums, and lookups.
- dict.items()Returns a view of (key, value) pairs, the most convenient way to loop over a dictionary.
- dict.get()Returns the value for a key, or a default value when the key is not in the dictionary.
- set.intersection()Returns a new set with the elements that appear in every given set.
- forA loop that goes through the successive items of a sequence or other iterable object.
Spotted a mistake or missing an example? Write to us.