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
For those interested in the ternary operator (also called a conditional expression), here is a way to use it to accomplish half of the original goal:
q = d[x] if x in d else {}
The conditional expression, of the form x if C else y
, will evaluate and return the value of either x
or y
depending on the condition C
. The result will then be assigned to q
.