dict.keys()
Returns a live view of a dictionary's keys, in the order they were added. Loop over it, test it with in, or turn it into a list.
dict.keys()keys() gives you all the keys of a dictionary. The keys come out in insertion order: the order in which they were first added.
The result is not a list but a view: a window onto the dictionary. It updates by itself when the dictionary changes, and it cannot be indexed with [0]. Wrap it in list() when you need a real list.
You often do not need keys() at all: for k in d: already loops over the keys, and k in d already tests them. Key views do have one extra trick: they support set operations such as & and -, which is a quick way to compare the keys of two dictionaries.
Return value
A dict_keys view of the dictionary's keys.
Examples
1List the keys
capitals = {"France": "Paris", "Peru": "Lima", "Japan": "Tokyo"}
print(capitals.keys())
print(list(capitals.keys()))dict_keys(['France', 'Peru', 'Japan']) ['France', 'Peru', 'Japan']
2The view updates by itself
stock = {"pens": 4}
names = stock.keys()
print(len(names))
stock["ink"] = 2
print(names)
print(len(names))1 dict_keys(['pens', 'ink']) 2
3Compare the keys of two dictionaries
Key views behave like sets. Sort the result, because a set's order is not fixed.
jan = {"Ana": 120, "Ben": 80, "Chloe": 95}
feb = {"Ben": 60, "Chloe": 110, "Dan": 70}
print("Both months:", sorted(jan.keys() & feb.keys()))
print("Only January:", sorted(jan.keys() - feb.keys()))Both months: ['Ben', 'Chloe'] Only January: ['Ana']
4Keys in alphabetical order
ages = {"Omar": 28, "Ines": 34, "Yuki": 22}
for name in sorted(ages):
print(name, ages[name])Ines 34 Omar 28 Yuki 22
sorted(ages) sorts the keys; you do not need ages.keys() for that.
Common mistakes
Indexing the view
A keys view has no positions, so d.keys()[0] raises a TypeError. Convert it first, or use next(iter(d)) for the first key.
d = {"a": 1, "b": 2}
first = list(d.keys())[0]
print(first)
print(next(iter(d)))a a
Deleting keys while looping over the view
Changing the size of a dictionary while looping over it raises RuntimeError. Loop over a copy: for k in list(d):.
cart = {"apple": 0, "pear": 3, "kiwi": 0}
for k in list(cart):
if cart[k] == 0:
del cart[k]
print(cart){'pear': 3}Questions people ask
How do I check if a key exists in a dictionary?
Use if key in d:. It is fast and you do not need .keys().
How do I get the keys as a list?
list(d) or list(d.keys()); both give the same list.
Are dictionary keys ordered?
Yes, since Python 3.7 they keep the order in which they were first added.