TypeError: 'dict_keys' object is not subscriptable (tested fix)

TypeError: 'dict_keys' object is not subscriptable means you wrote d.keys()[0]. In Python 3, keys(), values() and items() return views that can't be indexed. We reproduced all three in Python 3.13 and tested the fixes.

1. keys(), values() and items() return views, not lists

In Python 3 these methods return live view objects. You can loop over them and test membership, but you can't index them:

d = {"b": 2, "a": 1}
for expr in ["d.keys()[0]", "d.values()[0]", "d.items()[0]"]:
    try:
        eval(expr)
    except TypeError as e:
        print(f"{expr:14} TypeError: {e}")

Output:

d.keys()[0]    TypeError: 'dict_keys' object is not subscriptable
d.values()[0]  TypeError: 'dict_values' object is not subscriptable
d.items()[0]   TypeError: 'dict_items' object is not subscriptable

2. The fix: list() or next(iter())

d = {"b": 2, "a": 1}
print(list(d)[0], list(d.values())[0], list(d.items())[0])   # copy to a list, then index
print(next(iter(d)), next(iter(d.values())))                 # first item without a full copy
print(sorted(d)[0])                                          # dicts keep insertion order, not sorted order

Output:

b 2 ('b', 2)
b 2
a

list(d)[0] works but copies every key. next(iter(d)) gets the first one without a copy. Note that "first" means first inserted: dicts keep insertion order (here "b"), so use sorted(d) if you want alphabetical. In Python 2, keys() returned a list, which is why old code and tutorials index it directly. For the general error, see object is not subscriptable.

Frequently asked questions

How do I get the first key of a dict in Python 3?

next(iter(d)) without copying, or list(d)[0]. It is the first inserted key.

Why did d.keys()[0] work in old code?

In Python 2, keys() returned a list. Python 3 returns a view, which can't be indexed.

How do I fix 'dict_values' object is not subscriptable?

Wrap it in list(): list(d.values())[0], or use next(iter(d.values())).

Written with AI assistance. Measured on 2026-10-22 on Debian with Python 3.13.5: indexing keys(), values() and items(), and the list(), next(iter()) and sorted() fixes. Every block was run verbatim and its output pasted unedited. PlainHeaders is our extension; Python is free.