在Python 3中的字典理解

2024-05-15 08:03:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我在Python2.7Python 3+中找到了关于dict理解的以下堆栈溢出帖子:Create a dictionary with list comprehension in Python,声明我可以像这样应用字典理解:

d = {key: value for (key, value) in sequence}

我在Python 3中试过。然而,这引发了一个例外。

d = {'a':1, 'b':2, 'c':3, 'd':4}
{key : value for (key, value) in d}
{key : value for key, value in d}

两个版本都提出了一个ValueError来表示ValueError: need more than 1 value to unpack

在Python3中,最简单/最直接的方法是什么?


Tags: keyin声明fordictionary字典value堆栈
3条回答

上面说得很好-如果你这样做的话,你可以在Python3中放置物品:

{key: d[key] for key in d}

d = {'a':1, 'b':2, 'c':3, 'd':4}
z = {x: d[x] for x in d}
z
>>>{'a': 1, 'b': 2, 'c': 3, 'd': 4}

这也提供了使用条件的能力

y = {x: d[x] for x in d if d[x] > 1}
y
>>>{'b': 2, 'c': 3, 'd': 4}

享受吧!

字典理解是指通过某种逻辑在字典中生成项:

x = {p: p*p for p in range(10)}

print(x)

y = {q: q*3 for q in range(5,15) if q%2!=0}

print(y)

在字典上循环只产生键。使用d.items()循环键和值:

{key: value for key, value in d.items()}

您看到的ValueError异常是不是一个dict理解问题,也不限于Python 3;您将在Python 2或常规的for循环中看到相同的问题:

>>> 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

因为每次迭代只产生一个项。

如果没有转换,{k: v for k, v in d.items()}只是一个冗长而昂贵的d.copy();只有在对键或值做更多的处理,或者使用条件或更复杂的循环构造时,才使用dict理解。

相关问题 更多 >