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?
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
Use iterkeys:
data.iterkeys().next()
'foo'
Presuming you are using python 2
For python2 or python 3
k, = data.keys()
print (k)
'foo'
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