In Python 3.x, dict.keys()
does not return a list, it returns an iterable (specifically, a dictionary view). It is worth noting that dict
itself is also an iterable of the keys.
If you want to obtain the first key, use next(iter(dict))
instead. (Note that before Python 3.6 dictionaries were unordered, so the 'first' element was an arbitrary one. Since 3.6 it will be based on insertion order. If you need that behaviour in older versions or with cross-version compatibility, you can use collections.OrderedDict
).
This works quite simply: we take the iterable from the dictionary view with iter()
, then use next()
to advance it by one and get the first key.
If you need to iterate over the keys—then there is definitely no need to construct a list:
for key in dict:
...
These are all advantageous when compared to using list()
as it means a list isn't constructed - making it faster and more memory efficient (hence why the default behaviour of keys()
was changed in 3.x). Even in Python 2.x you would be better off doing next(iter(dict.iterkeys())
.
Note all these things apply to dict.values()
and dict.items()
as well.