Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract key name from single element dictionary in Python

If I know my dictionaries will always have a single element, is there a way to extract the key name without going through a list? I'm currently doing it this way.

data = {'foo': [1, 2, 3]}
key_name = data.keys()[0]

Is there a more efficient technique?

like image 393
bholben Avatar asked Apr 27 '26 16:04

bholben


2 Answers

Iterating dictionary yields keys.

Using next, iter:

>>> data = {'foo': [1, 2, 3]}
>>> next(iter(data))
'foo'

Benchmark:

In [1]: data = {'foo': [1, 2, 3]}

In [2]: %timeit next(iter(data))
1000000 loops, best of 3: 197 ns per loop

In [3]: %timeit data.keys()[0]
10000000 loops, best of 3: 155 ns per loop

In [4]: %timeit data.iterkeys().next()
1000000 loops, best of 3: 226 ns per loop

In [9]: %timeit k, = data.keys()
10000000 loops, best of 3: 151 ns per loop

In [10]: %timeit k, = data    # <--- fastest
10000000 loops, best of 3: 81.4 ns per loop
like image 112
falsetru Avatar answered Apr 30 '26 04:04

falsetru


Use iterkeys:

data.iterkeys().next()
'foo'

Presuming you are using python 2

For python2 or python 3

k, = data.keys()
print (k)
'foo'
like image 41
Padraic Cunningham Avatar answered Apr 30 '26 05:04

Padraic Cunningham



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!