Ternary Operator with a dictionary [python]

1.6k views Asked by At

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?

1

There are 1 answers

4
Selcuk On BEST ANSWER

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:

d = {} if i == 0 else {**d, j: d.get(j, 0) + 1}

Starting with Python 3.9 you can do the following:

d = {} if i == 0 else d | {j: d.get(j, 0) + 1}