Python字典理解 [英] Python Dictionary Comprehension
问题描述
没有列表推导,你可以使用这样的东西:
l = []
在范围(1,11)中的n:
l.append(n)
我们可以将其缩短到列表推导: l = [n for range in range 1,11)]
。
但是,假设我要将字典的键设置为相同的值。
我可以做:
d = {}
为范围内的n(1,11):
d [n] = True#每个
的相同值
我已经尝试过: / p>
d = {}
d [i for range in range(1,11)] = True
但是,我在 SyntaxError
> 。
另外(我不需要这部分,但只是想知道),你可以设置一个字典的键到一堆不同的值,如下所示:
d = {}
为范围(1,11)中的n:
d [n] = n
这是否可以用字典理解?
d = {}
d [i for range in range(1,11)] = [x for x in range(1,11 )]
这也引发了一个 SyntaxError
的。
> >> d = {n:n ** 2 for n in range(5)}
>>>>打印d
{0:0,1:1,2:4,3:9,4:16}
如果要将它们全部设置为True:
>>> d = {n:范围(5)中的n的真值}
>>> print d
{0:True,1:True,2:True,3:True,4:True}
您似乎要求的是一种在现有字典上一次设置多个键的方法。没有直接的捷径。您可以像已经显示的一样循环,也可以使用字典理解创建一个新值,然后再执行 oldDict.update(newDict)
来合并新的价值观成为旧的。
Is it possible to create a dictionary comprehension in Python (for the keys)?
Without list comprehensions, you can use something like this:
l = []
for n in range(1, 11):
l.append(n)
We can shorten this to a list comprehension: l = [n for n in range(1, 11)]
.
However, say I want to set a dictionary's keys to the same value. I can do:
d = {}
for n in range(1, 11):
d[n] = True # same value for each
I've tried this:
d = {}
d[i for i in range(1, 11)] = True
However, I get a SyntaxError
on the for
.
In addition (I don't need this part, but just wondering), can you set a dictionary's keys to a bunch of different values, like this:
d = {}
for n in range(1, 11):
d[n] = n
Is this possible with a dictionary comprehension?
d = {}
d[i for i in range(1, 11)] = [x for x in range(1, 11)]
This also raises a SyntaxError
on the for
.
There are dictionary comprehensions in Python 2.7+, but they don't work quite the way you're trying. Like a list comprehension, they create a new dictionary; you can't use them to add keys to an existing dictionary. Also, you have to specify the keys and values, although of course you can specify a dummy value if you like.
>>> d = {n: n**2 for n in range(5)}
>>> print d
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
If you want to set them all to True:
>>> d = {n: True for n in range(5)}
>>> print d
{0: True, 1: True, 2: True, 3: True, 4: True}
What you seem to be asking for is a way to set multiple keys at once on an existing dictionary. There's no direct shortcut for that. You can either loop like you already showed, or you could use a dictionary comprehension to create a new dict with the new values, and then do oldDict.update(newDict)
to merge the new values into the old dict.
这篇关于Python字典理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!