Extract key name from single element dictionary in Python

后端 未结 3 419
-上瘾入骨i
-上瘾入骨i 2021-01-21 16:34

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.



        
相关标签:
3条回答
  • 2021-01-21 16:34

    Assuming you'll also need the value at some point, the most "pythonic" and robust way would probably be to use a try...except block like this:

    data = {'foo': [1, 2, 3]}
    try:
        key, value = data.items()[0]
    except IndexError:
        raise Exception("Your dictionary didn't have the element you thought it had")
    

    Here, you're simply converting your dictionary into a list of 2-tuples (using items) and picking out the first one of these, catching the case where there are no items. If the dictionary does have more than one item, any of the key:value pairs might be returned and your results will be indeterminate.

    Without discussing your specific use case -- which you are obviously far more familiar with than I -- it's worth pointing out that even when you expect a data structure to have particular contents, there will almost always be edge cases where that assumption is false and handling those exceptions gracefully will make for more robust code.

    This code should work in both Python 2 and 3 and given that in your regular case there is only one item available, the iteritems method will give negligible advantage in Python 2 over its standard counterpart, items.

    Edit:

    To expand on this point of efficiency (items vs iteritems in Python 2) the following (quick and dirty) timings show a very slight advantage of the former over the latter:

    $ python2.7 -m timeit "data = {'foo': [1, 2, 3]}; _ = data.items()[0]"
    1000000 loops, best of 3: 0.316 usec per loop
    $ python2.7 -m timeit "data = {'foo': [1, 2, 3]}; _ = next(data.iteritems())"
    1000000 loops, best of 3: 0.377 usec per loop
    

    Furthermore, extracting both the key and value at the same time gives a slight extra saving over taking one at a time.

    0 讨论(0)
  • 2021-01-21 16:40

    Use iterkeys:

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

    Presuming you are using python 2

    For python2 or python 3

    k, = data.keys()
    print (k)
    'foo'
    
    0 讨论(0)
  • 2021-01-21 16:53

    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
    
    0 讨论(0)
提交回复
热议问题