0

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?

Selcuk
  • 57,004
  • 12
  • 102
  • 110
Daniel
  • 21
  • 4
  • 1
    The conditional expression is not a shortened version of an if statement. They do different things, and a conditional expression is not always suitable. – khelwood Sep 27 '20 at 22:58

1 Answers1

3

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}
Selcuk
  • 57,004
  • 12
  • 102
  • 110
  • @Daniel Look [here](https://docs.python.org/3/library/stdtypes.html#typesmapping): "Dictionaries can be created by placing a comma-separated list of key: value pairs within braces". This is happening here via `**`. You could also do: `d = {} if i == 0 else {**d, j: d.get(j, 0) + 1}`. – Timus Sep 28 '20 at 00:11
  • @Timus Correct, that's a more concise way to write it. Updated my answer. – Selcuk Sep 28 '20 at 00:24
  • It is not equivalent. This one creates a new dictionary in the "else", the original mutates an existing dict. Also I don't think we should indulge users asking for dumb one-liners on here, so I downvoted, sorry! – wim Sep 28 '20 at 00:33
  • @wim All good. You are right, it is not equivalent but functionally closest that can be implemented using the ternary operator. There is also the disclaimer stating that this is _not_ the better method. – Selcuk Sep 28 '20 at 00:37