Roland's homepage

My random knot in the Web

Getting the first or last item from a dictview without a list

In this article we will discuss a faster and more efficient way to get only the first item from a view object in Python.

Problem

In a program I was using the following code to get the first key from a dict, via a view object.

firstkey = list(data.keys())[0]

Since the dict in question has about 67000 items in it, this takes a significant amount of time.

In [11]: %timeit list(data.keys())[0]
745 µs ± 2.5 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

Also, the intermediate list is quite big.

In [12]: import sys

In [13]: sys.getsizeof(list(data.keys()))
Out[13]: 536440

That’s 523 KiB allocated to get one number. There has to be a better way.

Solution

We use a combination of iter() and next().

firstkey = next(iter(data.keys()))

Not only is this significantly faster.

In [17]: %timeit next(iter(data.keys()))
140 ns ± 0.0378 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

It also uses much less memory.

In [18]: sys.getsizeof(iter(data.keys()))
Out[18]: 72

As a bonus, this also works for the last element in the view using reversed() instead of iter().

In [19]: next(iter(data.keys()))
Out[19]: 5

In [20]: next(reversed(data.keys()))
Out[20]: 67052

For comments, please send me an e-mail.


Related articles


←  Examining an OpenSSH ECDSA public key Python 3.11 speed comparison with 3.9  →