Reputation: 2933
>>> x = True
>>> a={ 1:198 if x else 2:198}
File "<stdin>", line 1
a={ 1:198 if x else 2:198}
^
SyntaxError: invalid syntax
Even adding braces does not help.
>>> a={ (1:198) if x else (2:198) }
File "<stdin>", line 1
a={ (1:198) if x else (2:198) }
^
SyntaxError: invalid syntax
Upvotes: 0
Views: 70
Reputation: 122116
The origin of the error is that, as Python is parsing the input, it will go something like this:
{
# dictionary or set
{ 1:
# dictionary where key is 1
{ 1: 198 if x else 2
# dictionary where key is 1 and the value is either 198 or 2, depending on x
{ 1: 198 if x else 2:
# wat?
That's why the caret indicates the colon; it's encountering a colon where it either expects either:
As it looks like you're only trying to change the key according to x
, you need to put the ternary expression in the key position:
{
# dictionary or set
{ 1 if x else 2:
# dictionary where key is either 1 or 2, depending on x
{ 1 if x else 2: 198
# dictionary where key is either 1 or 2, depending on x, and the value is 198
{ 1 if x else 2: 198 }
# OK!
Upvotes: 1
Reputation: 3765
You still can use dict with just enough braces
dict([(1, 198) if x else (2, 198)])
or
{1: 198} if x else {2: 198}
or, for longer cases
d = {}
d.update({1: 198} if x else {2: 198})
Upvotes: 1