danicotra
danicotra

Reputation: 1433

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] (same as list(mydict)[0])

  2. next(iter(mydict.keys())) (same as 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.

Upvotes: 26

Views: 50373

Answers (3)

alick
alick

Reputation: 327

Since the question assumes the dictionary has only one key-value pair, I'd like to add two more methods besides the accepted answer.

  • Use dict.popitem()[0]. popitem() returns the only key-value pair in tuple: (key, value). If you do not want to mutate the original dictionary, make a copy first.
  • Build a set and then pop: set(mydict).pop().

Simple performance comparisons in Python 3.9.6:

In [11]: import timeit

In [12]: timeit.timeit(stmt='d={1:2}; d.popitem()[0]')
Out[12]: 0.15144950605463237

In [13]: timeit.timeit(stmt='d={1:2}; next(iter(d))')
Out[13]: 0.1860927080269903

In [14]: timeit.timeit(stmt='d={1:2}; set(d).pop()')
Out[14]: 0.19704585697036237

In [15]: timeit.timeit(stmt='d={1:2}; list(d)[0]')
Out[15]: 0.2412048210389912

Upvotes: 9

Chris
Chris

Reputation: 22953

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.

Upvotes: 42

Ajax1234
Ajax1234

Reputation: 71451

To get the "first" key-value pair from a dictionary, you will have to use an OrderedDict:

from collections import OrderedDict
d = OrderedDict()

#add items as normal

first_key = [a for a, b in d.items()][0]
print(d[first_key])

Upvotes: 3

Related Questions