I just tried a list comprehension like this
[i if i==0 else i+100 for i in range(0,3)]
and it worked, but when I tried a similar dict comprehension, it throws an error:
d={3:3}
{d[i]:0 if i==3 else d[i]:True for i in range(0,4) }
What could be the reason? How can I use dict comprehension using if else
?
The error this produces:
{d[i]:0 if i==3 else d[i]:True for i in range(0,4) }
^
SyntaxError: invalid syntax
Note: The example I used here is just a random one, not my actual code. I can do this with alternative an solution, but I'm only looking at dict comprehensions now to learn.
You are using a conditional expression. It can only be used in places that accept expressions.
In a dictionary comprehension, the key and value parts are separate expressions, separated by the
:
(so the:
character is not part of the expressions). You can use a conditional expression in each one of these, but you can't use one for both.You only need to use it in the value part here:
However, you'll get a
KeyError
exception because thed
dictionary has no0
,1
, and2
keys.See the Dictionary displays section of the expression reference documentation: