Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to get a single key from a dictionary?

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:

  1. list(mydict.keys())[0]

  2. 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.

like image 865
danicotra Avatar asked Sep 04 '17 18:09

danicotra


1 Answers

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.

like image 193
Christian Dean Avatar answered Sep 28 '22 20:09

Christian Dean