0 votes
1 view
in Python by (40.4k 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 (92.9k 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

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...