How to extract dictionary single key-value pair in variables

后端 未结 10 1717
别那么骄傲
别那么骄傲 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)]
    

提交回复
热议问题