Having a python dictionary and knowing it is made of just one key/value pair, what's the best way to retrieve that single/unique item?
So far I know I could use one of these two ways:
list(mydict.keys())[0]
next(iter(mydict))
As far as I understand, list
performances are worse than iter
ones so the latter approach should be better, right? Which ways is best? There's something that's even better than the two way I indicated? Please let me know.
Which way is best?
I recommend using next(iter(d))
over list(mydict.keys())[0]
to retrieve a key from a dictionary. As you suspected, using next(iter(d))
is much better in terms of efficiency.
The efficiency difference can be observed by timing each method:
>>> import timeit
>>> setup='from string import ascii_letters; d = {k: v for k, v in enumerate(ascii_letters)}'
>>> timeit.timeit(stmt='list(d.keys())[0]', setup=setup)
1.0895291733333334
>>> timeit.timeit(stmt='next(iter(d))', setup=setup)
0.2682935466666656
The choice of using next(iter(d))
over list(d.keys())[0]
becomes very, very obvious as the size of the dictionary increases:
>>> setup='d = {k: v for k, v in enumerate(range(500, 10000))}'
>>> timeit.timeit(stmt='list(d.keys())[0]', setup=setup)
98.52252842666667
>>> timeit.timeit(stmt='next(iter(d))', setup=setup)
0.2720192000000452
next(iter(d))
performs so much better than list(d.keys())[0]
mainly because it avoids creating a potential huge list of all of the dictionaries keys in memory, when it really only needs the first element.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With