Python Ternary Operator with Assignment – Duplicate Issue

python

I am new to python. I'm trying to write this

if x not in d:
    d[x] = {}
q = d[x]

in a more compact way using the ternary operator

q = d[x] if x in d else (d[x] = {})

but this gives the syntax error. What am I missing?

Best Answer

The conditional operator in Python is used for expressions only, but assignments are statements. You can use

q = d.setdefault(x, {})

to get the desired effect in this case. See also the documentation of dict.setdefault().

Related Question