I want to optimize the code below to a one line
if i == 0:
d = {}
else:
d[j] = d.get(j, 0) + 1
i tried solving it using a ternary operator but it gave me an error
d = {} if i == 0 else d[j] = d.get(j, 0) + 1
The error :
d = {} if i == 0 else d[j] = d.get(j, 0) + 1 ^ SyntaxError: cannot assign to conditional expression
Can it be solved using ternary operator or is there another way to make it in a one line?
For reference, here is a one liner. I wouldn't call it an improvement though as your original
if
/else
method is much more readable:Starting with Python 3.9 you can do the following: