How to extract dictionary single key-value pair in variables

后端 未结 10 1698
别那么骄傲
别那么骄傲 2020-12-08 06:33

I have only a single key-value pair in a dictionary. I want to assign key to one variable and it\'s value to another variable. I have tried with below ways but I am getting

10条回答
  •  伪装坚强ぢ
    2020-12-08 07:27

    If you just want the dictionary key and don't care about the value, note that (key, ), = foo.items() doesn't work. You do need to assign that value to a variable.

    So you need (key, _), = foo.items()

    Illustration in Python 3.7.2:

    >>> foo = {'a': 1}
    >>> (key, _), = foo.items()
    >>> key
    'a'
    >>> (key, ), = foo.items()
    Traceback (most recent call last):
      File "", line 1, in 
    ValueError: too many values to unpack (expected 1)
    

提交回复
热议问题