Python 3 中的字典理解 [英] Dictionary Comprehension in Python 3
问题描述
我发现了以下关于 Python2.7
和 Python 3+
中的 dict 推导式的堆栈溢出帖子:在 Python 中创建一个带有列表推导式的字典 声明我可以像这样应用字典推导式:
d = {key: value for (key, value) in sequence}
我在 Python 3 中尝试过.但是,它引发了一个异常.
d = {'a':1, 'b':2, 'c':3, 'd':4}{key : d 中 (key, value) 的值}{key : 键值,d 中的值}
两个版本都提出了一个 ValueError
说 ValueError: 需要超过 1 个值来解包
.
在 Python3 中进行字典理解最简单/最直接的方法是什么?
循环字典只会产生键.使用 d.items()
循环遍历键和值:
{key:key的值,d.items()中的值}
您看到的 ValueError
异常不是字典理解问题,也不限于 Python 3;您会在 Python 2 或常规 for
循环中看到同样的问题:
因为每次迭代只会产生一个项目.
如果没有转换,{k: v for k, v in d.items()}
只是一个冗长而昂贵的d.copy()
;仅当您对键或值执行更多操作,或者使用条件或更复杂的循环结构时,才使用 dict 推导式.
I found the following stack overflow post about dict comprehensions in Python2.7
and Python 3+
: Create a dictionary with list comprehension in Python stating that I can apply dictionary comprehensions like this:
d = {key: value for (key, value) in sequence}
I tried it in Python 3. However, it raises an exception.
d = {'a':1, 'b':2, 'c':3, 'd':4}
{key : value for (key, value) in d}
{key : value for key, value in d}
Both versions raise a ValueError
saying that ValueError: need more than 1 value to unpack
.
What is the easiest / the most direct way to make a dictionary comprehension in Python3?
Looping over a dictionary only yields the keys. Use d.items()
to loop over both keys and values:
{key: value for key, value in d.items()}
The ValueError
exception you see is not a dict comprehension problem, nor is it limited to Python 3; you'd see the same problem in Python 2 or with a regular for
loop:
>>> d = {'a':1, 'b':2, 'c':3, 'd':4}
>>> for key, value in d:
... print key, value
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
because each iteration there is only one item being yielded.
Without a transformation, {k: v for k, v in d.items()}
is just a verbose and costly d.copy()
; use a dict comprehension only when you do a little more with the keys or values, or use conditions or a more complex loop construct.
这篇关于Python 3 中的字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!