Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python ternary operator failure on dictionary [closed]

Tags:

python

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?

like image 892
kgf3JfUtW Avatar asked Dec 07 '25 05:12

kgf3JfUtW


1 Answers

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
like image 79
Mohammed Aouf Zouag Avatar answered Dec 12 '25 09:12

Mohammed Aouf Zouag



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!