Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Python by (47.6k points)

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.

1 Answer

0 votes
by (106k points)

You can use the below-mentioned code for dictionary comprehension in Python:-

>>> d = {n: n**2 for n in range(5)} 

>>> print(d) 

{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}

Related questions

0 votes
1 answer
0 votes
4 answers
0 votes
1 answer

Browse Categories

...