v78
v78

Reputation: 2933

Origin of this error

>>> 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

Answers (2)

jonrsharpe
jonrsharpe

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:

  • a continuation of the expression defining the value;
  • a comma indicating the end of the current key-value pair and the beginning of the next; or
  • a closing curly brace indicating the end of the dictionary literal.

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

Serge
Serge

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

Related Questions