How to extract dictionary single key-value pair in variables

后端 未结 10 1668
别那么骄傲
别那么骄傲 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:19

    In Python 3:

    Short answer:

    [(k, v)] = d.items()
    

    or:

    (k, v) = list(d.items())[0]
    

    or:

    (k, v), = d.items()
    

    Long answer:

    d.items(), basically (but not actually) gives you a list with a tuple, which has 2 values, that will look like this when printed:

    dict_items([('a', 1)])
    

    You can convert it to the actual list by wrapping with list(), which will result in this value:

    [('a', 1)]
    
    0 讨论(0)
  • 2020-12-08 07:23
    >>> d = {"a":1}
    >>> [(k, v)] = d.items()
    >>> k
    'a'
    >>> v
    1
    

    Or using next, iter:

    >>> k, v = next(iter(d.items()))
    >>> k
    'a'
    >>> v
    1
    >>>
    
    0 讨论(0)
  • 2020-12-08 07:23
    d = {"a": 1}
    

    you can do

    k, v = d.keys()[0], d.values()[0]
    

    d.keys() will actually return list of all keys and d.values() return list of all values, since you have a single key:value pair in d you will be accessing the first element in list of keys and values

    0 讨论(0)
  • 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 "<stdin>", line 1, in <module>
    ValueError: too many values to unpack (expected 1)
    
    0 讨论(0)
提交回复
热议问题