Original code: for dictionary d1, if d1[w] does not exist, initialize it to 1. Increment it otherwise.
if d1.get(w) == None:
d1[w] = 1
else:
d1[w] += 1
However, using ternary operator fails on this.
d1[w] = 1 if d1.get(w) == None else d1[w] += 1
^
SyntaxError: invalid syntax
What is the issue here?
Change
d1[w] = 1 if d1.get(w) == None else d1[w] += 1
to
d1[w] = 1 if d1.get(w) == None else d1[w] + 1 # '+' instead of '+='
or, as @vaultah suggested in his comment :
d1[w] = d1.get(w, 0) + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With