Extract key name from single element dictionary in Python

后端 未结 3 416
-上瘾入骨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:40

    Use iterkeys:

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

    Presuming you are using python 2

    For python2 or python 3

    k, = data.keys()
    print (k)
    'foo'
    

提交回复
热议问题