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
.
Question&Answers:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…