How to extract dictionary single key-value pair in

2019-02-11 16:05发布

I have only a single key-value pair in 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 error for same.

>>> d ={"a":1}

>>> d.items()
[('a', 1)]

>>> (k,v) = d.items()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

>>> (k, v) = list(d.items())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack

I know that we can extract key and value one by one, or by for loop and iteritems(), but isn't there a simple way such that we can assign both in single statement?

7条回答
够拽才男人
2楼-- · 2019-02-11 16:36

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)]
查看更多
登录 后发表回答