如何在变量中提取词典单键值对 [英] How to extract dictionary single key-value pair in variables
问题描述
我在字典中只有一个键值对。我想要将键分配给一个变量
,它的值是另一个变量。我尝试过以下方法,但是我收到相同的错误。
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
我知道我们可以提取密钥和值,或者通过for循环和iteritems(),但是不是有一个简单的方法,以便我们可以在单个语句中分配?
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?
推荐答案
添加另一个级别,使用元组(只是逗号):
Add another level, with a tuple (just the comma):
(k, v), = d.items()
或列表:
[(k, v)] = d.items()
或选择第一个元素:
k, v = d.items()[0]
前两个如果您的字典有多个键,则它们会引发异常,并且都可以在Python 3上工作,而后者必须拼写为 k,v = next(iter(d.items( )))
工作。
The first two have the added advantage that they throw an exception if your dictionary has more than one key, and both work on Python 3 while the latter would have to be spelled as k, v = next(iter(d.items()))
to work.
演示:
>>> d = {'foo': 'bar'}
>>> (k, v), = d.items()
>>> k, v
('foo', 'bar')
>>> [(k, v)] = d.items()
>>> k, v
('foo', 'bar')
>>> k, v = d.items()[0]
>>> k, v
('foo', 'bar')
>>> k, v = next(iter(d.items())) # Python 2 & 3 compatible
>>> k, v
('foo', 'bar')
这篇关于如何在变量中提取词典单键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!