Python 如何提取变量中的字典单键值对
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20145902/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to extract dictionary single key-value pair in variables
提问by
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 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 a single statement?
我知道我们可以一个一个地提取键和值,或者通过 for 循环 and iteritems(),但是没有一种简单的方法可以让我们在一个语句中同时分配它们吗?
采纳答案by Martijn Pieters
Add another level, with a tuple (just the comma):
添加另一个级别,带有一个元组(只是逗号):
(k, v), = d.items()
or with a list:
或使用列表:
[(k, v)] = d.items()
or pick out the first element:
或者选择第一个元素:
k, v = d.items()[0]
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.
前两个具有额外的优势,如果您的字典有多个键,它们会抛出异常,并且两者都适用于 Python 3,而后者必须拼写为k, v = next(iter(d.items()))才能工作。
Demo:
演示:
>>> 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')
回答by Ignacio Vazquez-Abrams
You have a list. You must index the list in order to access the elements.
你有一个清单。您必须索引列表才能访问元素。
(k,v) = d.items()[0]
回答by Farhadix
items()returns a list of tuples so:
items()返回元组列表,因此:
(k,v) = d.items()[0]
回答by falsetru
>>> d = {"a":1}
>>> [(k, v)] = d.items()
>>> k
'a'
>>> v
1
Or using next, iter:
或使用next, iter:
>>> k, v = next(iter(d.items()))
>>> k
'a'
>>> v
1
>>>
回答by its me
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 dyou will be accessing the first element in list of keys and values
d.keys()实际上将返回所有键的d.values()列表并返回所有值的列表,因为您有一个键:值对,d您将访问键和值列表中的第一个元素
回答by kindall
This is best if you have many items in the dictionary, since it doesn't actually create a list but yields just one key-value pair.
如果字典中有很多项目,这是最好的,因为它实际上并没有创建一个列表,而是只产生一个键值对。
k, v = next(d.iteritems())
Of course, if you have more than one item in the dictionary, there's no way to know which one you'll get out.
当然,如果你的字典里有不止一项,你就没有办法知道你会找出哪一项。
回答by Eduard
In Python 3:
在 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:
d.items(), 基本上(但实际上不是)为您提供一个包含 2 个值的元组的列表,打印时看起来像这样:
dict_items([('a', 1)])
You can convert it to the actual list by wrapping with list(), which will result in this value:
您可以通过用 包装将其转换为实际列表list(),这将导致此值:
[('a', 1)]
回答by KevinG
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.
如果您只想要字典键而不关心值,请注意这(key, ), = foo.items()不起作用。您确实需要将该值分配给变量。
So you need (key, _), = foo.items()
所以你需要 (key, _), = foo.items()
Illustration in Python 3.7.2:
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)
回答by Kamlakar Ravindra Bhopatkar
key = list(foo.keys())[0]
value = foo[key]

